Des*_*tor 6 c++ string boolean language-lawyer implicit-conversion
我瞪着它并试图在SO上找到类似的问题,但没有找到任何有用的东西.所以,在这里发布我的问题.
考虑这个程序:
#include <iostream>
void foo(const std::string &) {}
int main()
{
foo(false);
}
Run Code Online (Sandbox Code Playgroud)
[Warning] converting 'false' to pointer type for argument 1 of 'std::basic_string::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits; _Alloc = std::allocator]' [-Wconversion-null]
为什么C++在没有显式强制转换的情 我原以为会遇到编译错误.由于以下异常显示,程序在运行时异常终止:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Run Code Online (Sandbox Code Playgroud)
关于这种隐式转换的标准是什么?
在C++ 11引入nullptr关键字之前,空指针有点像黑客.任何等于零的整数文字都可以作为空指针常量,并且false适合账单.
所以,你的程序的效果是std::string用一个char const *参数构造NULL.构造函数不支持空指针,因此您将获得未定义的行为.
这个问题的解决方案是使用更新的C++方言.-std=c++11必要时传递给编译器,或-std=c++14.然后你应该得到这样的东西:
Run Code Online (Sandbox Code Playgroud)error: no matching function for call to 'foo'
http://coliru.stacked-crooked.com/a/7f3048229a1d0e5a
编辑:嗯,GCC似乎还没有实现这一改变.这有点令人惊讶.你可以试试Clang.
我已经提交了一份错误报告.