Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `is_open()` non-const?

Tags:

I have a function similar to below which is const and needs to check that a file stream is open prior to continuing:

bool MyClass::checkSomeStuff() const {     // Where outputFile_ is a std::ofstream     if ( ! outputFile_.is_open() )     {         throw std::runtime_error( "Output file not open." );     }      // ... do more stuff 

However, It seems I can't do this as is_open() is declared as:

bool is_open ( ); 

(i.e. non-const)

To me it seems a bit odd that a function like this - which is clearly a pure accessor - should be non-const. Is there a logic behind it which makes sense?

like image 230
Component 10 Avatar asked Jul 13 '12 08:07

Component 10


1 Answers

It is in fact const in C++11. The C++03 version is an unfortunate error.

like image 105
Jon Avatar answered Oct 13 '22 12:10

Jon