C++ 中不同的构造语法总是让我有点困惑。在另一个问题 https://stackoverflow.com/questions/48255276/why-does-stdstring-x00-report-length-of-0/48255303,建议尝试像这样初始化一个字符串
std::string foo{ '\0' };
这可以工作并产生预期结果:长度为 1 且仅包含空字符的字符串。在测试代码时,我不小心输入了
std::string foo('\0');
这编译得很好(即使使用也没有警告-Wall
),但在运行时终止
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Aborted (core dumped)
现在,据我所知,没有构造函数 http://en.cppreference.com/w/cpp/string/basic_string/basic_string for std::string
它以单个字符作为参数,当我尝试间接传递该字符时,这个假设得到了进一步证实。
char b = '\0';
std::string a(b);
这会产生一个不错的、冗长的编译错误。正如这个
std::string a('z');
所以我的问题是:什么允许std::string a('\0');
编译,以及它与std::string a{ '\0' };
?
Footnote: Compiling using g++
on Ubuntu. This doesn't strike me as a compiler bug, but just in case...
特点'\0'
可以隐式转换为整数值0
从而代表实现定义的空指针常量. This:
std::string foo('\0');
调用接受类型指针的构造函数重载const char*
作为参数并导致未定义的行为。
就相当于通过了0
or NULL
:
std::string foo(0); // UB
std::string bar(NULL); // UB
The 参考 http://en.cppreference.com/w/cpp/string/basic_string/basic_string对于第四个和第五个构造函数重载状态:
如果 s... 包括 s 是 a 的情况,则行为未定义无效的
指针.
第二个声明:
std::string foo{'\0'}; // OK
调用构造函数接受std::initializer_list<char>
作为参数并且不会导致 UB。
您可以调用构造函数重载接受count数量char
改为:
std::string s(1, '\0');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)