Horstmann’s C++ pitfalls tackles an interesting point when talking about streams. To quote him:
Use conversion to
void*, not conversion tointorbool, to implement objects yielding truth values. Unlikeintorbool,void*have no legal operations other than==comparison.
As a programmer, I would be puzzled if some function returned void* when I expect a boolean. Horstmann provides an example where using a void* instead of a bool seems appropriate. Is it always advisable?
This is not advised in general circumstances and, with C++11, is not advised at all.
The reason for the conversion to void* was to support syntax like
std::ifstream myStream;
if (myStream) {
}
if (!myStream) {
}
Here, a conversion to bool seems more reasonable, but leads to weirdnesses like this:
if (myStream == true) // ??
The conversion to void* prevents this code from being legal, but opens up a whole other can of worms, like
delete myStream; // ??
In C++11, with the ability to have explicit operator bool() as a member function, this void* hack is deprecated and should not be used. Don't use this idiom. If you need something to return a bool, have it return a bool. If you need an object that can be converted to a bool, use explicit operator bool.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With