std::string initialization with a bool

谁说我不能喝 提交于 2019-12-10 20:15:27

问题


Consider the following initialization:

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

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

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

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

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

EDIT:

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

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]


回答1:


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

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.

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



来源:https://stackoverflow.com/questions/32563648/stdstring-initialization-with-a-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!