问题描述
所以今天我写了一个很难发现的错误,其中我将std :: string初始化为nullptr(不是指向std :: string的指针,而是值本身)。我发现显然只有在C ++ 11或更高版本中才能使用clang。
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;
}
如您所见,我尝试将nullptr分配给a的随机实例类,它没有用。字符串中有什么魔术可以使它起作用,以及什至是有效的语法?我以为在这种情况下会遇到类型转换错误。
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
它没有任何形式的警告,尽管如果不使用C ++ 11则会出错,
It gave no form of warnings, though it would error out if not using C++11
推荐答案
这仅仅是因为存在(链接中的数字(5))和(链接中的数字(3))用于接受 const char *
,因此 nullptr
匹配。
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.
在C ++ 11之前(因此在 nullptr
)之前,当您尝试从 0
或进行构造时,会发生相同的问题。 NULL
。所有这些情况都是非法的,并导致不确定的行为,尽管至少一个STL(RogueWave?)过去接受了它并生成了一个空字符串。
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.
这篇关于为什么可以将nullptr分配给std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!