Why implicit conversion of bool to string isn't an error?

前端 未结 3 1641
失恋的感觉
失恋的感觉 2021-01-12 22:24

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:

#         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-12 22:28

    What happens is that an std::string is implicitly constructed from false, using the const CharT* overload and converting false to a null pointer. According to the documentation for that constructor :

    The behavior is undefined if s [the pointer] does not point at an array of at least Traits::length(s)+1 elements of CharT.

    Hence the malfunctioning (in the form of a friendly exception, but don't rely on it).

    Now, is it correct ? According to [conv.ptr] :

    A null pointer constant is an integer literal (2.13.2) with value zero or a prvalue of type std::nullptr_t.

    false has indeed a value of zero, but is not an integer literal (it's a boolean literal). The implicit conversion to the CharT* that std::string's constructor takes is thus non-standard.

    And indeed, while GCC emits a warning, Clang refuses to compile it.

提交回复
热议问题