Why can you assign nullptr to std :: string?

So, today I wrote it is quite difficult to find an error in which I initialized std :: string nullptr (not a pointer to std :: string, but the value itself). I found that this can only be done in C ++ 11 or later with clang.

#include <string> #include <iostream> using namespace std; class Meh{ int x; }; class Foo { private: std::string x=nullptr; Meh y=nullptr; //remove this line and it compiles public: std::string z=nullptr; }; int main(void) { Foo f; cout << fz; return 0; } 

As you can see, I tried to assign nullptr only to a random instance of the class, and it did not work. What is the magic in the line that allows this to work, and how is this even valid syntax? I assumed that in this case I will be met with a type selection error.

For reference, I compiled with this:

 clang++ test.cpp -O3 -g -fno-inline -std=c++11 -Wall 

He did not give any warnings, although he might be mistaken if not using C ++ 11

+6
source share
1 answer

This is simply because there are constructors (number (5) in the link) and assignment operators (number (3) in the link) for std::string , which accept const char* , and therefore correspond to nullptr .

Before C ++ 11 (and therefore before nullptr ), the same problem arose when you tried to build from 0 or NULL . All these cases were illegal and led to undefined behavior, at least one STL (RogueWave?) Accepted it in the past and generated an empty string.

+13
source

Source: https://habr.com/ru/post/987305/


All Articles