Conversion of false to object via const char * constructor

后端 未结 3 1043
广开言路
广开言路 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条回答
  •  梦谈多话
    2021-01-20 16:44

    The OP 's program fails in compilation in g++ & clang++ when use -std=c++11, -std=c++14.

    See live demo here on g++ 6.1.0. It gives following error

    prog.cc: In function 'A foo()':
    prog.cc:17:12: error: could not convert 'false' from 'bool' to 'A'
         return false;
                ^~~~~ 
    

    See live demo here on clang++. It gives following diagnosis.

    main.cpp:17:12: error: no viable conversion from returned value of type 'bool' to function return type 'A'
        return false;
               ^~~~~
    main.cpp:1:7: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'bool' to 'const A &' for 1st argument
    class A
          ^
    main.cpp:1:7: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'bool' to 'A &&' for 1st argument
    class A
          ^
    main.cpp:10:4: note: candidate constructor not viable: no known conversion from 'bool' to 'const char *' for 1st argument
    A::A(const char *s)
       ^
    main.cpp:22:12: error: no viable conversion from returned value of type 'bool' to function return type 'A'
        return true;
               ^~~~
    main.cpp:1:7: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'bool' to 'const A &' for 1st argument
    class A
          ^
    main.cpp:1:7: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'bool' to 'A &&' for 1st argument
    class A
          ^
    main.cpp:10:4: note: candidate constructor not viable: no known conversion from 'bool' to 'const char *' for 1st argument
    A::A(const char *s)
       ^
    main.cpp:7:21: warning: private field 'p' is not used [-Wunused-private-field]
            const char *p;
                        ^
    

    false should not convert to pointer type since C++11. See similar question here which I've asked sometimes ago.

提交回复
热议问题