Reputation: 3
I came across this code in my reading:
void assure(std::ifstream& infile ) {
if(!infile) { /* stuff */}
}
I tested for curiosity using function argument types ifstream&
and ifstream
, and it seems to work. I was curious how the conditional expression might work. Is this a case of NULL object or empty object? I thought C++ object could not be NULL?
Since !infile
works, how is a failed ifstream
object represented?
Thanks for the ensuing enlightenment.
Upvotes: 0
Views: 399
Reputation: 129314
It won't make any great difference, no. Both will result in very similar code the same behaviour. The difference is in the behaviour on eof
, which good
will return false
for, where operator!
sees that as a true
. However, this makes little difference in most cases, as the failbit
will be set in the fstream
state if an attempt to read past the end of file is made - there are some cases when this doesn't happen, but most of the time, it's the same thing.
Upvotes: 0
Reputation: 96258
It uses the negate operator, and it is simply hooked to the fail()
check.
It's not entirely the opposite of good()
, as that one also checks for EOF (eofbit
).
(And yes, a reference always points to an object, the question is meaningless, only a pointer can be NULL).
Upvotes: 2