为什么可以将 nullptr 赋值给 std::string?
Why can you assign nullptr to std::string?
所以今天我写了一个很难找到的错误,我将 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;
}
如您所见,我尝试将 nullptr 分配给 class 的随机实例,但没有成功。 string 中有什么魔力可以让它发挥作用,这种甚至有效的语法以什么方式存在?我假设在这种情况下我会遇到类型转换错误。
作为参考,我用这个编译:
clang++ test.cpp -O3 -g -fno-inline -std=c++11 -Wall
它没有给出任何形式的警告,但如果不使用 C++11 会出错
这仅仅是因为 constructors (number (5) in the link) and assignment operators (number (3) in the link) for std::string
接受 const char*
,因此 nullptr
匹配。
在 C++11 之前(因此在 nullptr
之前),当您尝试从 0
或 NULL
构造时会出现同样的问题。所有这些情况都是非法的并导致未定义的行为,尽管过去至少有一个 STL(RogueWave?)接受了它并生成了一个空字符串。
所以今天我写了一个很难找到的错误,我将 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;
}
如您所见,我尝试将 nullptr 分配给 class 的随机实例,但没有成功。 string 中有什么魔力可以让它发挥作用,这种甚至有效的语法以什么方式存在?我假设在这种情况下我会遇到类型转换错误。
作为参考,我用这个编译:
clang++ test.cpp -O3 -g -fno-inline -std=c++11 -Wall
它没有给出任何形式的警告,但如果不使用 C++11 会出错
这仅仅是因为 constructors (number (5) in the link) and assignment operators (number (3) in the link) for std::string
接受 const char*
,因此 nullptr
匹配。
在 C++11 之前(因此在 nullptr
之前),当您尝试从 0
或 NULL
构造时会出现同样的问题。所有这些情况都是非法的并导致未定义的行为,尽管过去至少有一个 STL(RogueWave?)接受了它并生成了一个空字符串。