3

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?

8
  • 1
    It's advisable when is a good idea, and it is inadvisable if it is a bad idea. What sort of answer did you expect?
    – Kerrek SB
    Feb 3, 2012 at 20:15
  • @KerrekSB: cases, examples, to be able to distinguish between the good practices and the bad practices, I’m a bit confused right now. Why don’t we always do that? Why don’t we just typedef void* secure_bool
    – qdii
    Feb 3, 2012 at 20:17
  • 2
  • Horstmann is talking about conversion operators, not return types. Your question makes no sense.
    – ildjarn
    Feb 3, 2012 at 20:23
  • @ildjarn : The statement Unlike int or bool, void* have no legal operations other than == comparison is what I’m referring to, regardless of conversions.
    – qdii
    Feb 3, 2012 at 20:25

1 Answer 1

10

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!

2
  • Has the definition of istream changed in C++11 to use this new feature?
    – Kerrek SB
    Feb 3, 2012 at 20:27
  • 2
    @Kerrek: yes. It's a breaking change, but one that only breaks broken code (delete std::cin won't compile anymore). Feb 3, 2012 at 20:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.