why is std::cout convertible to void* if using g++?

邮差的信 提交于 2019-11-30 11:43:41
nicebyte

Read this (your question is answered in the very last section, "The safe bool problem").

To elaborate a bit, the implementation defines an implicit conversion to void* defined for things like std::cin and std::cout, just so that code like while(std::cin>>x){...} compiles, while code like int x = std::cin; doesn't. It's still problematic because you can write stuff like in your example.

C++11 solves this problem by introducing explicit conversions.

An explicit conversion operator looks like this:

struct A {
 explicit operator B() { ... } // explicit conversion to B
};

When A has an explicit conversion to B, code like this becomes legal:

A a;
B b(a);

However, code like this is not:

A a;
B b = a;

A construct like if(std::cin) requires cin to be converted to bool, the standard states that in order for the conversion to be valid in that particular case, code like bool x(std::cin); should be "legal". Which can be achieved by adding an explicit conversion to bool. It allows cin/cout to be used in the above context, while avoiding things like int x = std::cout;.

For more information, refer to Bjarne's page as well as this question.

Answering only the follow-up, since nicebyte's answer is perfect for the original question.

Chances are, your gcc is set up to use libstdc++ (which hasn't changed the operator yet due it being an ABI-breaking change), and your clang is set up to use libc++ (which was from the beginning intended as a C++11 standard library and isn't quite conformant in C++98 mode - it provides a bool conversion operator that is explicit in C++11).

I think it's to allow for if (std::cout) ... without allowing for implicit conversion to bool, or something like that.

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