为什么布尔到字符串的隐式转换不是一个错误? [英] Why implicit conversion of bool to string isn't an error?

查看:455
本文介绍了为什么布尔到字符串的隐式转换不是一个错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我瞪大眼睛资讯科技及电讯;试图找到类似的问题上也是如此,但没有发现任何有用的东西。所以,在这里发布我的问题。

考虑此程序:

 的#include<&iostream的GT;
无效美孚(常量标准::字符串&安培;){}
诠释的main()
{
    富(假);
}
【警告】转换'假',以指针类型为'的std :: basic_string的&LT参数1; _CharT,_Traits,_Alloc> :: basic_string的(常量_CharT *,常量_Alloc和放大器;)与_CharT =字符; _Traits =的std :: char_traits<焦炭取代; _Alloc =的std ::分配器<烧焦>][-Wconversion空]

为什么C ++允许这种没有明确的投?我期待得到编译器错误。该程序在运行时异常终止,由于异常显示以下内容:

 抛'的std :: logic_error的一个实例后终止叫
  什么():basic_string的:: _ S_construct空无效此应用程序已请求运行时终止它以一种不寻常的方式。
请联系应用程序的支持团队以获取更多信息。

什么标准说有关此类型的隐式转换?


解决方案

C ++ 11之前推出的 nullptr 关键字,空指针是一个黑客攻击的一位。任何整数文字等于零足以作为一个空指针常数,适合该法案。

所以,你的程序的作用是构建的std ::字符串字符常量* 参数的 NULL 。构造函数不支持空指针,所以你得到了一个未定义的行为。

这个问题的解决办法是用C的更新方言++。通 -std = C ++ 11 编译器如果有必要,或 -std = C ++ 14 。那么你应该得到的东西是这样的:


 错误:调用'富'不匹配函数


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

编辑:嗯,GCC不会出现实现这种变化呢。这是一个有点出人意料。您可以尝试锵。

提起的bug报告。

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<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' [-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.

这篇关于为什么布尔到字符串的隐式转换不是一个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆