Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using void* instead of bool an advisable practice?

Horstmann’s C++ pitfalls tackles an interesting point when talking about streams. To quote him:

Use conversion to void*, not conversion to int or bool, to implement objects yielding truth values. Unlike int or bool, 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?

like image 802
qdii Avatar asked Dec 19 '25 23:12

qdii


1 Answers

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!

like image 184
templatetypedef Avatar answered Dec 21 '25 12:12

templatetypedef