std :: string初始化与bool [英] std::string initialization with a bool

查看:369
本文介绍了std :: string初始化与bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下初始化:

std::string falseString = false;
std::string trueString = true;

有了 g ++ 5.2.0 falseString 的警告,而 trueString 的错误。

With g++ 5.2.0, compiler throws a warning for falseString, while an error for trueString.

使用 clang ++ 3.6 -std = c ++ 11 ,编译器会为 falseString c $ c> trueString 。

With clang++ 3.6 -std=c++11, compiler throws error for both falseString as well as trueString.

Q1)为什么 gcc 虽然两个初始化值都是相同的类型( bool )?

Q1) Why the different behavior with gcc even though both initialization values are of the same type (bool)?

Q2)哪个编译器是正确的,为什么?标准说了什么?

Q2) Which compiler is correct and why? What does the standard say?

编辑:


错误:从'bool'到'std :: string'(aka
'basic_string')

error: no viable conversion from 'bool' to 'std::string' (aka 'basic_string')

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

warning: converting 'false' to pointer type for argument 1 of 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits; _Alloc = std::allocator]' [-Wconversion-null]


推荐答案

对于初学者,你肯定不能从 true 初始化 std :: string 。这只是荒谬的。

For starters, you definitely cannot initialise a std::string from true. That's just nonsensical.

GCC 5.2接受来自 false 的初始化,与抗议,因为它曾经是一个有效空指针字面值。是啊。比较C ++ 03和C ++ 11之间的3.9.1 / 6— 如下所述,bool值表现为整数类型被删除。

GCC 5.2 is accepting the initialisation from false, with protest, because it used to be a valid null pointer literal. Yeah. Compare 3.9.1/6 between C++03 and C++11 — "as described below, bool values behave as integral types" was removed.

这两个编译器都应该出现错误,但 GCC在这方面出现了问题,直到一个月前(因此GCC 6.0)。

It should error on both compilers these days, but GCC was buggy in this regard until like a month ago (so GCC 6.0).

这篇关于std :: string初始化与bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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