【问题标题】:Best way to handle storing (possibly NULL) char * in a std::string在 std::string 中处理存储(可能为 NULL)char * 的最佳方法
【发布时间】:2010-04-30 10:38:44
【问题描述】:
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);
}

但这似乎有点乱。想法?

【问题讨论】:

  • 我想你会在其他地方读取string 的值。这段代码需要char const* 还是string
  • 你觉得哪里乱了?
  • @Thomas,你为什么这么问?我认为无论哪种方式,我的新类最好使用 STL...实际上我是从存储 C 字符串转换它,因为它使复制对象更容易出错...添加了一个新字段,默认情况下不复制!

标签: c++ stl char


【解决方案1】:

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

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

【讨论】:

  • 是的,我刚刚在调试时意识到 string::assign 不能按我的预期工作。
【解决方案2】:
void MyClass::setVar(const char *str) 
{ 
    if (str) {
       mStr.assign(str, str + std::min(strlen(str), maxLength) ); 
    } else {
       mStr = "";
    }
} 

【讨论】:

    猜你喜欢
    • 2011-01-09
    • 2017-08-04
    • 2016-01-21
    • 2023-03-31
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多