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?

Component 10
  • 10,247
  • 7
  • 47
  • 64
  • 1
    what could you do with a `const` stream? – Nim Jul 13 '12 at 08:20
  • 1
    Good discussion on this very subject here: http://gcc.gnu.org/ml/libstdc++/2004-08/msg00105.html – Paul R Jul 13 '12 at 08:21
  • 5
    @Nim: Probably not much, but that's not the point. The point is that the *operation* of checking whether the stream is open or not should not logically change it - it's just a check. My `checkSomeStuff` function is, and should be, const - it's an accessor. I would not want it to be non-const purely because `is_open()` is non-const - that doesn't seem right. – Component 10 Jul 13 '12 at 08:24
  • 1
    You can use `outputFile.rdbuf()->is_open()` instead if your compiler doesn't implement library DR 365 – Jonathan Wakely Jul 13 '12 at 08:36

3 Answers3

21

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

Jon
  • 428,835
  • 81
  • 738
  • 806
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

Leonard
  • 3,012
  • 2
  • 31
  • 52
-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.
Alex Medveshchek
  • 501
  • 4
  • 12
  • Wait... how does it being used after `open()` and `close()` mean it should be non-`const`? – flight Jul 13 '12 at 08:31
  • @devidark: Unfortunately `good()` is not a feasible substitute here as it fails to highlight if (a) the file has not yet been opened or (b) it has been opened and closed successfully. – Component 10 Jul 13 '12 at 08:43
  • @quasiverse: Because `open()`/`close()` are modify stream's state. @Component 10: Agree with you. But if your code is in consitence, you're get enough with `bool good() const`. ;) – Alex Medveshchek Jul 13 '12 at 08:46
  • @devidark Yes but `is_open()` doesn't modify the stream's state...(?) – flight Jul 13 '12 at 08:50
  • @quasiverse: If old `is_open()` is not `const`, then it doesn't get that guarantee. Isn't it? – Alex Medveshchek Jul 13 '12 at 08:53