Assign a nullptr to a std::string is safe?

青春壹個敷衍的年華 提交于 2019-11-27 15:59:26

Interesting little question. According to the C++11 standard, sect. 21.4.2.9,

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

Requires: s shall not be a null pointer.

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:

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

Or you could return const char* (it makes better sense):

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.

My question is if GetValue() returns NULL myString becomes an empty string? 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!