9

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 ?

1
  • 3
    The compiler is probably choosing the string(const char*) constructor. Commented Nov 7, 2013 at 20:27

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

16 Comments

Thank you very much for the downvote! Can you please explain why the answer was downvoted? Note the "... but it won't work." (I'll be more clear about that in a moment, though).
I don't understand the down-vote. This answer seems correct and hits on the important points. The only problem I can see is that the "won't work" may not be as obvious at a glance, so perhaps superficial readers are assuming the answer says string(0) is okay, when it's actually UB.
Huh, why would anyone downvote this? And then there's two of you? I'd love to know where you disagree with @Dietmar, because you're wrong (whoever you are).
@AdamH.Peterson: thanks. I updated with a bit of clarification.
@DietmarKühl, I think it would be fine to add both declarations. But perhaps just adding the void const * deleted overload would make string(nullptr) ambiguous, which may accomplish the same objective.
|
5

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.

1 Comment

Wow! That's kinda dangerous! But the original code is already broken, so I guess it's fine...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.