开发者

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

开发者 https://www.devze.com 2023-01-23 13:45 出处:网络
Consider the class foo with two constructors开发者_高级运维 defined like this: class foo { public:

Consider the class foo with two constructors开发者_高级运维 defined like this:

class foo
{
public:
    foo(const std::string& filename) {std::cout << "ctor 1" << std::endl;}
    foo(const bool some_flag = false) {std::cout << "ctor 2" << std::endl;}
};

Instantiate the class with a string literal, and guess which constructor is called?

foo a ("/path/to/file");

Output:

ctor 2

I don't know about you, but I don't find that the most intuitive behavior in programming history. I bet there is some clever reason for it, though, and I'd like to know what that might be?


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.


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).


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号