将nullptr分配给std :: string是安全的吗?

时间:2012-05-27 05:25:30

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

我正在开展一个小项目并遇到以下情况发生的情况:

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

我的问题是如果GetValue()返回NULL myString变为空字符串?这是不确定的?还是会发生段错?

3 个答案:

答案 0 :(得分:48)

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

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

要求:s不应为空指针。

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

答案 1 :(得分:9)

这是运行时错误。

你应该这样做:

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

答案 2 :(得分:4)

  

我的问题是如果GetValue()返回NULL myString变为空字符串?这是不确定的?还是会发生段错?

这是未定义的行为。编译器和运行时可以做任何想做的事情,但仍然符合要求。

相关问题