Why is there an implicit type conversion from pointers to bool in C++?

后端 未结 3 558
清酒与你
清酒与你 2020-11-30 13:28

Consider the class foo with two constructors defined like this:

class foo
{
public:
    foo(const std::string& filename) {std::cout <<         


        
相关标签:
3条回答
  • 2020-11-30 14:06

    It's very common in C to write this

    void f(T* ptr) {
        if (ptr) {
            // ptr is not NULL
        }
    }
    

    You should make a const char* constructor.

    0 讨论(0)
  • 2020-11-30 14:10

    You're passing a char* to the foo constructor. This can be implicitly converted to a boolean (as can all pointers) or to a std::string. From the compiler's point of view, the first conversion is "closer" than the second because it favours standard conversions (i.e. pointer to bool) over user provided conversions (the std::string(char*) constructor).

    0 讨论(0)
  • 2020-11-30 14:13

    You're confusing two issues. One is that "blah" can be implicitly converted to a string and the other is that const char* can be implicitly converted into a boolean. It's very logical to see the compiler go to the implicit conversion which minimizes the total amount of conversions necessary.

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