为什么布尔到字符串的隐式转换不是错误?

我戴上了它&也试图在 SO 上找到类似的问题,但没有发现任何有用的东西.所以,在这里发布我的问题.

考虑这个程序:

#include <iostream>void foo(const std::string &) {}主函数(){富(假);}

<上一页>[警告] 将 'false' 转换为 'std::basic_string::basic_string(const _CharT*, const _Alloc&) 的参数 1 的指针类型 [with _CharT = char;_Traits = std::char_traits;_Alloc = std::allocator]' [-Wconversion-null]

为什么 C++ 允许在没有显式转换的情况下这样做?我期待得到编译器错误.由于异常显示如下,程序在运行时异常终止:

在抛出 'std::logic_error' 实例后调用终止what(): basic_string::_S_construct null 无效此应用程序已请求运行时以不寻常的方式终止它.请联系应用程序的支持团队以获取更多信息.

标准对这种类型的隐式转换有何规定?

解决方案

在 C++11 引入 nullptr 关键字之前,空指针有点小题大做.任何等于 0 的整数文字都足以作为空指针常量,并且 false 符合要求.

因此,您的程序的效果是使用 NULLchar const * 参数构造 std::string.构造函数不支持空指针,因此您会得到未定义的行为.

解决此问题的方法是使用较新的 C++ 方言.如有必要,将 -std=c++11-std=c++14 传递给编译器.然后你应该得到这样的东西:

<块引用>

错误:没有匹配的函数调用 'foo'

http://coliru.stacked-crooked.com/a/7f3048229a1d0e5a

嗯,GCC 似乎还没有实施此更改.这有点令人惊讶.你可以试试 Clang.

我已经提交了错误报告.

I goggled it & tried to find similar question on SO also but didn't find anything useful. So, posting my question here.

Consider this program:

#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]

Why C++ allows this without explicit cast? I was expecting to get compiler error. The program abnormally terminates at runtime due to exception displaying following:

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.

What the standard says about this type of implicit conversion?

解决方案

Before C++11 introduced the nullptr keyword, null pointers were a bit of a hack. Any integer literal equal to zero would suffice as a null pointer constant, and false fit the bill.

So, the effect of your program is to construct the std::string with a char const * argument of NULL. The constructor doesn't support null pointers, so you get undefined behavior.

The solution to this problem is to use a newer dialect of C++. Pass -std=c++11 to the compiler if necessary, or -std=c++14. Then you should get something like this:

error: no matching function for call to 'foo'

http://coliru.stacked-crooked.com/a/7f3048229a1d0e5a

EDIT: Hmm, GCC doesn't appear to implement this change yet. That's a bit surprising. You might try Clang.

I've filed a bug report.

相关文章