ani*_*ita 5 c++ string constructor type-conversion
在我的代码中,有一个拼写错误:而不是"false"在初始化std::string对象时使用,我键入false(这是一个bool).现在这没有报告任何编译错误.但是后来在我的代码中,当使用这个字符串对象时,我std::logic_error在运行时得到了.任何人都可以解释,为什么在这种情况下允许构造(否则我会收到编译错误,并在那里发现问题)?
这是一个小片段 -
#include <iostream>
int main ()
{
std::string str = false;
std::cout << str << "\n";
}
Run Code Online (Sandbox Code Playgroud)
运行时我得到的o/p -
xhdrdevl8@~/MYBACKUP=>g++ -o test_string -g test_string.cxx
xhdrdevl8@~/MYBACKUP=>./test_string
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct NULL not valid
Aborted
Run Code Online (Sandbox Code Playgroud)
std::string有一个构造函数,它接受一个const char*以null结尾的字符串.
false可以用作空指针常量,因为它是一个值为零的整型常量表达式,因此使用此std::string构造函数.
将空指针传递给此构造函数会产生未定义的行为.标准库实现通过生成logic_error异常来帮助您std::string通过向它传递空指针来通知您违反了构造函数的约束.其他实现可能没那么有用(您可能会立即崩溃或数据损坏或谁知道什么).