Why can you assign nullptr to std::string?

别等时光非礼了梦想. 提交于 2019-12-19 07:07:22

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/30268904/why-can-you-assign-nullptr-to-stdstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!