Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return NULL instead of std::string C++

Tags:

c++

return

I have this function:

std::string SWindows::PRecv(int rc, std::string* ip);

In this function, in some case I return NULL and the code compile (IDE : VS 2012). For me, NULL it's not a std::string object so we can't write that.

So why it's correct to return NULL when the return of the function is a std::string ?

like image 866
Bob Avatar asked Nov 07 '13 20:11

Bob


2 Answers

The value NULL is equivalent to 0 in C++ and 0 is a perfectly valid char const* constant. The string class has a non-explicit constructor taking char const*, i.e. the compiler will compile the code but it won't work: that is, although the compiler excepts the code, it is undefined behavior.

Looking at the definition in C++11 I don't see a deleted overload taking a std::nullptr_t, i.e., it will also compile when converting from a nullptr. I would have hoped that there would be a deleted overload taking a std::nullptr_t which would allow the compiler to catch the situation, at least, when passing nullptr.

like image 83
Dietmar Kühl Avatar answered Oct 22 '22 05:10

Dietmar Kühl


What you're doing is constructing a std::string from a char const* equal to 0 (or NULL).

This is actually prohibited by the standard:

[C++11: 21.4.2/9] Requires: s shall not be a null pointer

However, GCC is extra-kind to you and does checks to make it a no-op. It is not required to and you shouldn't ever rely on this.

like image 21
Lightness Races in Orbit Avatar answered Oct 22 '22 05:10

Lightness Races in Orbit