0

The C++ standard I/O stream class ios defines two overloaded operator ! and void* that are used to check the stream's state.

For example:

ifstream fin("hello.txt");
if (fin)  {} // ios::operator void*() is called
if (!fin) {} // ios::operator !() is called

However, I think two overloaded operators are overdid. Why not just one overloaded function operator bool()?

It is likely because I/O stream classes were widely used before bool became one of C++ keywords. In other words, keep them there just for backward compatibility.

If just for backward compatibility, why are they not marked as deprecated? If not for backward compatibility, then for what?

xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • 4
    It's more likely to be the safe bool idiom. If there was an operator bool, you could assign an ifstream to any numeric type. The safe bool idiom is obsolete in C++11 because you can make `operator bool` explicit. – Pseudonym Feb 21 '13 at 03:08
  • Thanks to Pseudonym. Your link is very useful. – xmllmx Feb 21 '13 at 03:11
  • 3
    It's more than deprecated, `basic_ios::operator void*` isn't even part of C++ anymore (as of C++11) – Cubbi Feb 21 '13 at 03:40
  • @Pseudonym - `operator void*()` is one of the poster children that the "safe bool" proponents point to as a justification for their paranoia. Just think, you might accidentally write `delete std::cout;` and it would compile and run! – Pete Becker Feb 21 '13 at 12:38
  • @Pete Becker - There are varying levels of safe bool proponents. I used it for things that a programmer could actually confuse for numbers. Think of big integers, for example. You would certainly like to test if a big integer is nonzero with `if (n)`, but you certainly don't want that implicitly converted to an integer, because that would mean something different. – Pseudonym Feb 21 '13 at 23:25
  • @Pseudonym - for a large integer type, a conversion to `void*` avoids conversion to an integer. – Pete Becker Feb 22 '13 at 13:54
  • I know. I was talking about a non-explicit conversion to bool, which would have been inappropriate in that case. – Pseudonym Feb 22 '13 at 22:09
  • The whole premise of this question, as written in 2013, is wrong. The C++ standard does not define `operator void*` for streams. (An earlier version did...) – Ben Voigt Sep 04 '13 at 17:09

0 Answers0