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

bar*_*des 23 c++ string c++-standard-library

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

std::string myString;
#GetValue() returns a char*
myString = myObject.GetValue();
Run Code Online (Sandbox Code Playgroud)

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

thb*_*thb 49

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

basic_string(const charT* s, const Allocator& a = Allocator());
Run Code Online (Sandbox Code Playgroud)

要求:s不应为空指针.

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


Naw*_*waz 9

这是运行时错误.

你应该做这个:

myString = ValueOrEmpty(myObject.GetValue());
Run Code Online (Sandbox Code Playgroud)

其中ValueOrEmpty定义为:

std::string ValueOrEmpty(const char* s)
{
    return s == nullptr ? std::string() : s;
}
Run Code Online (Sandbox Code Playgroud)

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

const char* ValueOrEmpty(const char* s)
{
    return s == nullptr ? "" : s; 
}
Run Code Online (Sandbox Code Playgroud)

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


Dav*_*men 7

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

这是未定义的行为。编译器和运行时可以做任何它想做的事情并且仍然是合规的。


康桓瑋*_*康桓瑋 7

Update:

Since C++23 adopted P2166, it is now forbidden to construct std::string from nullptr, that is, std::string s = nullptr or std::string s = 0 will no longer be well-formed.