简体   繁体   English

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

[英]Assign a nullptr to a std::string is safe?

I was working on a little project and came to a situation where the following happened:我正在做一个小项目,遇到了以下情况:

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

My question is if GetValue() returns NULL myString becomes an empty string?我的问题是如果GetValue()返回 NULL myString变成空字符串? Is it undefined?它是未定义的吗? or it will segfault?或者它会发生段错误?

Interesting little question. 有趣的小问题。 According to the C++11 standard, sect. 根据C ++ 11标准,教派。 21.4.2.9, 21.4.2.9,

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

Requires: s shall not be a null pointer. 要求:s不应为空指针。

Since the standard does not ask the library to throw an exception when this particular requirement is not met, it would appear that passing a null pointer provoked undefined behavior. 由于标准不要求库在不满足此特定要求时抛出异常,因此传递空指针似乎会引发未定义的行为。

It is runtime error. 这是运行时错误。

You should do this: 你应该做这个:

myString = ValueOrEmpty(myObject.GetValue());

where ValueOrEmpty is defined as: 其中ValueOrEmpty定义为:

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

Or you could return const char* (it makes better sense): 或者你可以返回const char* (它更有意义):

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

If you return const char* , then at the call-site, it will convert into std::string . 如果返回const char* ,那么在调用站点,它将转换为std::string

My question is if GetValue() returns NULL myString becomes an empty string? 我的问题是如果GetValue()返回NULL myString变成一个空字符串? Is it undefined? 这是不确定的? or it will segfault? 还是会发生段错?

It's undefined behavior. 这是未定义的行为。 The compiler and run time can do whatever it wants and still be compliant. 编译器和运行时可以做任何想做的事情并且仍然符合要求。

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 .由于 C++23 采用了P2166 ,现在禁止从nullptr构造std::string ,即std::string s = nullptrstd::string s = 0不再是合式的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM