我用谷歌搜索并试图在 SO 上找到类似的问题,但没有找到任何有用的东西。所以,在这里发布我的问题。
考虑这个程序:
#include <iostream>
void foo(const std::string &) {}
int main()
{
foo(false);
}
[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.
标准对这种类型的隐式转换有何规定?
在 C++11 引入之前nullptr
关键字、空指针有点像黑客。任何等于零的整数文字都足以作为空指针常量,并且false
符合要求。
所以,你的程序的效果是构建std::string
with a char const *
的论证NULL
。构造函数不支持空指针,因此您会得到未定义的行为。
此问题的解决方案是使用更新的 C++ 方言。经过-std=c++11
如有必要,给编译器,或者-std=c++14
。那么你应该得到这样的东西:
error: no matching function for call to 'foo'
http://coliru.stacked-crooked.com/a/7f3048229a1d0e5a
EDIT:嗯,GCC 似乎还没有实施此更改。这有点令人惊讶。你可以试试 Clang。
I've filed错误报告。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)