Why is there an implicit type conversion from poin

2019-01-15 18:12发布

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?

3条回答
贪生不怕死
2楼-- · 2019-01-15 18:31

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.

查看更多
欢心
3楼-- · 2019-01-15 18:47

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

查看更多
何必那么认真
4楼-- · 2019-01-15 18:50

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.

查看更多
登录 后发表回答