在 std::string 中处理存储(可能为 NULL) char * 的最佳方法

发布于 2024-08-30 20:58:06 字数 369 浏览 1 评论 0原文

class MyClass
{
 public:
  void setVar(const char *str);
 private:
  std::string mStr;
  int maxLength; //we only store string up to this length
};

当外部代码很可能为空字符串传入 NULL(并且无法更改)时,实现 setVar 的最佳方法是什么?我目前做的事情有点像:

void MyClass::setVar(const char *str)
{
 mStr.assign(str ? str : "",maxLength);
}

但看起来有点乱。想法?

class MyClass
{
 public:
  void setVar(const char *str);
 private:
  std::string mStr;
  int maxLength; //we only store string up to this length
};

What's the best approach to implement setVar when the external code is quite likely to pass in NULL for an empty string (and cannot be changed)? I currently do something a bit like:

void MyClass::setVar(const char *str)
{
 mStr.assign(str ? str : "",maxLength);
}

But it seems kind of messy. ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小情绪 2024-09-06 20:58:07
void MyClass::setVar(const char *str) 
{ 
    if (str) {
       mStr.assign(str, str + std::min(strlen(str), maxLength) ); 
    } else {
       mStr = "";
    }
} 
void MyClass::setVar(const char *str) 
{ 
    if (str) {
       mStr.assign(str, str + std::min(strlen(str), maxLength) ); 
    } else {
       mStr = "";
    }
} 
樱花坊 2024-09-06 20:58:06

您发布的代码不正确,因为它始终会从源字符串中读取 maxLength 个字符。特别是,这意味着当 str 为 NULL 时,它将读取空字符串的末尾。假设 str 以 null 结尾,这将起作用:

void MyClass::setVar(const char *str)
{
    if (str==NULL)
        mStr.clear();
    else
        mStr.assign(str, std::min(strlen(str), maxLength));
}

The code you posted is incorrect, as it will always read maxLength characters from the source string. In particular, this means it will read past the end of the empty string when str is NULL. This will work instead, assuming str is null-terminated:

void MyClass::setVar(const char *str)
{
    if (str==NULL)
        mStr.clear();
    else
        mStr.assign(str, std::min(strlen(str), maxLength));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文