Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you assign nullptr to std::string?

So today I wrote a fairly hard to find bug where I initialized a std::string to nullptr (not a pointer to std::string, but the value itself). I've found apparently it's only possible to do 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 << f.z;
    return 0;
}

As you can see, I tried assigning nullptr to just a random instance of a class and it didn't work. What magic is in string that allows this to work, and in what way is this even valid syntax? I assumed I would be met with a type casting error in this case.

For reference I compiled with this:

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

It gave no form of warnings, though it would error out if not using C++11

like image 411
Earlz Avatar asked May 15 '15 21:05

Earlz


1 Answers

That's simply because there are constructors (number (5) in the link) and assignment operators (number (3) in the link) for std::string that accept a const char*, and hence the nullptr matches.

Before C++11 (and therefore before nullptr), the same problem occurred when you tried to construct from 0 or NULL. All those cases were illegal and result in undefined behaviour, although at least one STL (RogueWave?) accepted it in the past and generated an empty string.

like image 142
Daniel Frey Avatar answered Oct 12 '22 01:10

Daniel Frey