24

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?

4

3 回答 3

21

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

于 2012-07-13T08:21:46.550 回答
13

This is a known discrepancy in the standard library. You can find more information about it over here: http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#365

于 2012-07-13T08:21:07.630 回答
-1
  • Let's see on CPPReference, what is is_open() for:

The stream is associated with a file if either a previous call to member open succeeded or if the object was successfully constructed using the parameterized constructor, and close has not been called since.

So, use it immediately after open() / close(). That is why the old is_open() non-const. ;)

  • Use bool good() const instead.
于 2012-07-13T08:23:30.327 回答