Reputation: 9619
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]
Upvotes: 3
Views: 983
Reputation: 385284
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).
Upvotes: 6