Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 567
bardes Avatar asked May 27 '12 05:05

bardes


People also ask

Can std::string be Nullptr?

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.

Can we assign a string to another string in C++?

A string is a one dimensional character array that is terminated by a null character. The value of a string can be copied into another string. This can either be done using strcpy() function which is a standard library function or without it.

How do you declare a null string in C++?

The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0'). When we write some string using double quotes (“…”), then it is converted into null terminated strings by the compiler.


2 Answers

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.

like image 139
thb Avatar answered Sep 28 '22 10:09

thb


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.

like image 28
Nawaz Avatar answered Sep 28 '22 08:09

Nawaz