Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么可以将nullptr分配给std::string?_C++_String_C++11_Standards - Fatal编程技术网

C++ 为什么可以将nullptr分配给std::string?

C++ 为什么可以将nullptr分配给std::string?,c++,string,c++11,standards,C++,String,C++11,Standards,所以今天我写了一个很难找到的bug,其中我将std::string初始化为nullptr(不是指向std::string的指针,而是值本身)。我发现,显然,只有在C++11或更高版本中使用clang才能实现 #include <string> #include <iostream> using namespace std; class Meh{ int x; }; class Foo { private: std::string x=nullptr; M

所以今天我写了一个很难找到的bug,其中我将std::string初始化为nullptr(不是指向std::string的指针,而是值本身)。我发现,显然,只有在C++11或更高版本中使用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;
}

它没有给出任何形式的警告,尽管如果不使用C++11,它会出错,这仅仅是因为有(链接中的数字(5)和(链接中的数字(3))接受
const char*
,因此
nullptr
匹配


在C++11之前(因此在
NULL ptr
之前),当您尝试从
0
NULL
构造时,也会出现相同的问题。尽管过去至少有一个STL(RogueWave?)接受了它并生成了一个空字符串,但所有这些情况都是非法的,并导致未定义的行为。

值得注意的是,这是未定义的行为™@Earlz
nullptr
在C++11之前是不存在的。@Earlz因为C++98/C++03没有
nullptr
@DanielFrey啊,我想是标准库通过一些nullptr\t类型提供了nullptr仿真,我认为这只是一个空白*我不认为这回答了为什么的问题,只是不同的问题,而不是如何解决的问题。原因是没有很好的理由,这是一个设计错误/疏忽
std::basic_string
是一个非常复杂的野兽,但大多数复杂性都与或多或少无用的东西有关;稍微增加一点安全性是值得的,因为复杂性的边际增加。
clang++ test.cpp -O3 -g -fno-inline -std=c++11 -Wall