25

Due to a bug, I just found out that this code compiles fine on with Visual Studio 17 and probably on other compilers as well. Now I'm curious why?

#include <iostream> #include <string> std::string foo(){ return nullptr; } int main(){ auto s = foo(); std::cout << s << std::endl; } 

I could imagine it is because the std::basic_string c'tor could be invoked with a char* and while returning an implicit conversion from ptr to std::string occurs (with NULL as argument and then goes poof). Am I on the right way?

4

2 Answers 2

24

Yes, your assumption is right, checking std::basic_string constructors #5 will be called:

basic_string( const CharT* s, const Allocator& alloc = Allocator() ); 

Note that passing nullptr invokes undefined behavior as stated in the standard and the notes :

The behavior is undefined if [s, s + Traits::length(s)) is not a valid range (for example, if s is a null pointer).

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

1 Comment

Interesting enough, std::string_view's constructor has attribute__((__nonnull)) and the compiler emits a warning when NULL or nullptr is passed to the std::string_view's constructor. I wonder, why there is no such attribute for std::string's constructor
13

Why shouldn't it compile? std::string has the following constructor:

string(const CharT* s, const Allocator& alloc = Allocator()); 

that constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The constructor is not explicit, so the implicit conversion from nullptr to std::string is indeed possible.

2 Comments

Please note that passing null is UB
@RichardCritten, it definitely is. But the question was why this code compiles, not what happens if the code is executed. UB will happen not only for nullptr, but for any pointer that doesn't point to the beginning of a null-terminated string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.