Narrowing conversion to bool in list-initialization - strange behaviour

后端 未结 1 1931
情深已故
情深已故 2020-12-08 20:39

Consider this piece of C++11 code:

#include 

struct X
{
    X(bool arg) { std::cout << arg << \'\\n\'; }
};

int main() 
{
    d         


        
相关标签:
1条回答
  • 2020-12-08 21:16

    This simply looks like a bug, if we try the following:

    bool b {3} ;
    

    both gcc and clang issue a diagnostic, for example gcc says:

    warning: narrowing conversion of '3' from 'int' to 'bool' inside { } [-Wnarrowing]

    This is covered in the draft C++11 standard by section 8.5.4 List-initialization paragraph 7 which says:

    A narrowing conversion is an implicit conversion

    [...]

    • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type.

    This is same paragraph that covers your example and the following simpler example:

    bool a {3.0} ;
    

    which would be covered by this bullet from paragraph 7 quoted above:

    • from a floating-point type to an integer type, or

    From paragraph 3, this is ill-formed an requires a diagnostic:

    List-initialization of an object or reference of type T is defined as follows:

    [...]

    • Otherwise, if the initializer list has a single element, the object or reference is initialized from that element; if a narrowing conversion (see below) is required to convert the element to T, the program is ill-formed.

    which gcc produces no diagnostic but clang does provide the following warning, although not the narrowing conversion warning we should see:

    warning: implicit conversion from 'double' to 'bool' changes value from 3 to true [-Wliteral-conversion]

    Note, section 3.9.1 [basic.fundamental] says:

    Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types.48 A synonym for integral type is integer type.

    You should file a bug report with both clang and gcc.

    Jonathan Wakely notes that the EDG compiler gives a narrowing error for the OPs code, which is a strong indication that this indeed should produce a diagnostic.

    Update

    I submitted a gcc and clang bug report.

    The clang bug report has been updated as fixed:

    Fixed in r229792.

    The gcc bug report has been updated as fixed:

    Fixed.

    and a live example seems to confirm this.

    0 讨论(0)
提交回复
热议问题