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 ?
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 delete
d 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 delete
d overload taking a std::nullptr_t
which would allow the compiler to catch the situation, at least, when passing nullptr
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With