【问题标题】:Assign a nullptr to a std::string is safe?将 nullptr 分配给 std::string 是否安全?
【发布时间】:2012-06-02 01:35:14
【问题描述】:

我正在做一个小项目,遇到了以下情况:

std::string myString;
#GetValue() returns a char*
myString = myObject.GetValue();

我的问题是如果GetValue() 返回NULL myString 变成一个空字符串?它是未定义的吗?还是会出现段错误?

【问题讨论】:

  • 这个问题很相似:stackoverflow.com/questions/2407711/…
  • 微软总是有一个错误,将 0x0 分配给 std::string 是可以的。通过查看您的代码,您似乎是一个微软人,所以它可能对您有用。但是.. 否则会触发 SIGSEGV。

标签: c++ string c++-standard-library


【解决方案1】:

有趣的小问题。根据 C++11 标准,第 11 节。 21.4.2.9,

basic_string(const charT* s, const Allocator& a = Allocator());

要求:s 不能是空指针。

由于标准不要求库在不满足此特定要求时抛出异常,因此传递空指针似乎会引发未定义的行为。

【讨论】:

    【解决方案2】:

    这是运行时错误。

    你应该这样做:

    myString = ValueOrEmpty(myObject.GetValue());
    

    其中ValueOrEmpty 定义为:

    std::string ValueOrEmpty(const char* s)
    {
        return s == nullptr ? std::string() : s;
    }
    

    或者你可以返回const char*(这更有意义):

    const char* ValueOrEmpty(const char* s)
    {
        return s == nullptr ? "" : s; 
    }
    

    如果您返回const char*,那么在调用站点,它将转换为std::string

    【讨论】:

      【解决方案3】:

      我的问题是如果 GetValue() 返回 NULL myString 变成一个空字符串?它是未定义的吗?还是会出现段错误?

      这是未定义的行为。编译器和运行时可以为所欲为,并且仍然是合规的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-27
        • 2021-11-07
        • 1970-01-01
        • 1970-01-01
        • 2020-02-12
        • 2020-11-04
        相关资源
        最近更新 更多