Conversion of false to object via const char * constructor

后端 未结 3 1017
广开言路
广开言路 2021-01-20 15:59

I have built the following minimal example:

class A
{
    public:
        A(const char *s);

    private:
        const char *p;
};

A::A(const char *s)
  :          


        
3条回答
  •  -上瘾入骨i
    2021-01-20 16:47

    As published, C++ 11 has the rule "an integral constant expression prvalue of integer type which evaluates to 0 can be converted to any pointer type, yielding the null pointer value of that type." (C++98/03 had a similarly worded rule with the same net effect).

    bool is an integer type, and false evaluates to 0. So false is a valid null pointer constant.

    Apart from this extra rule, C++ has no implicit conversions from integral types to pointers. Which is why true cannot implicitly be converted to a pointer.

    However, C++14 changed the definition of a null pointer constant so that only integer literals (and not integral constant expressions) qualify. false is a boolean literal, not an integer one, so under C++14, the code will not compile.

    Furthermore, since the issue was recognised by the standard committee as a defect in C++11, newer C++11 compilers are likely to obey the C++14 rules in this regard and not treat false as a null pointer constant. Thanks to @Destructor for tracking down the issue status.


    As to why two implicit conversions seem to be allowed here: the rule is not "at most one implicit conversion is allowed." The rule is "at most one user-defined conversion is allowed." Pointer conversions (such as converting a null pointer constant to a null pointer value) are not classified as user-defined conversions. So the conversion sequence in your case is a pointer conversion (bool to const char *) followed by a user-defined conversion (const char * to A).

提交回复
热议问题