Assign a nullptr to a std::string is safe?
Asked Answered
B

4

44

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?

Barefoot answered 27/5, 2012 at 5:25 Comment(2)
This question is pretty similar: #2408211Woodwork
Microsoft always had a bug where assigning a 0x0 to std::string was OK. By looking at your code it seems like you are a microsoft guy, so it might work for you. But.. otherwise it would trigger a SIGSEGV.Ryder
B
72

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.

Bridgetbridgetown answered 27/5, 2012 at 5:48 Comment(0)
D
14

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.

Duiker answered 27/5, 2012 at 5:46 Comment(0)
B
9

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.

Blackshear answered 1/5, 2022 at 16:21 Comment(2)
This answer seems to refer to initialization at compile time, but it does not tell what will happen when the nullptr is returned from a function where the compiler cannot deduce the value at compile time (as scetched in the question),Inexplicable
So now our constructors have to look like this trash "MyClass( const char *internal_name ) : name{ internal_name ? internal_name : "" } {} Yet another reason to avoid the everything everywhere all at once "standard" library.Behistun
W
8

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.

Waitress answered 27/5, 2012 at 5:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.