'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? Is it undefined? or it will segfault?
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | David Hammen |
| Solution 3 | 康桓瑋 |
