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

狂风中的少年 提交于 2019-11-27 19:06:58

问题


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? Is it undefined? or it will segfault?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/10771864/assign-a-nullptr-to-a-stdstring-is-safe

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