Reputation: 579
I want to know, how these objects convert to bool. I mean what the compiler relies on when casting. On bit flags? As I think it works like that: the compiler checks the flags and if !goodbit then returns false else true. For example:
#include <iostream>
#include <fstream>
int main() {
std::ifstream file("someDir.txt");
if(!file) { \\ Checks the flags? If !goodbit (eofbit, badbit or failbit) return false else true?
\\some code
}
return 0;
P.S. I have bad English, sorry
Upvotes: 0
Views: 828
Reputation: 1231
The compiler uses the operator bool
to convert the stream to a boolean. In the documentation you can read that std::basic_ios<CharT,Traits>::operator bool
Checks whether the stream has no errors.
1) Returns a null pointer if
fail()
returnstrue
, otherwise returns a non-null pointer. This pointer is implicitly convertible to bool and may be used in boolean contexts.2) Returns
true
if the stream has no errors and is ready for I/O operations. Specifically, returns !fail().
There is a really helpful table on the same page that details which bits (eofbit, failbit, badbit
) result in fail()
returning true or false.
Upvotes: 1