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

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-26 14:48:33

问题


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?


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/4111495/why-is-there-an-implicit-type-conversion-from-pointers-to-bool-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!