Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't it a compile-time error to return a nullptr as a std::string?

Tags:

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?

like image 702
Taron Avatar asked Jun 17 '19 11:06

Taron


1 Answers

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).

like image 196
Hatted Rooster Avatar answered Sep 23 '22 04:09

Hatted Rooster