Search code examples
c++constantsmutableconst-correctness

Implementing const methods of an interface and file reading


I have an interface that has bunch of const methods. In one of the implementation of the interface I need to read the requested information from a file. As pointed out for example here it is in fact NOT a const operation because the file handle changes with reading.

There are basically three options to go about this I am aware of:

1) Use temporary file handle on every request.

2) Use PIMPL.

3) Use mutable on the file handle.

The first option is obviously an overkill and with lots of requests adds lots of overhead. The second option adds indirection but seems to be pretty standard solution. The third option however has no overhead and no indirection but it is basically a blank cheque for changes. Then again though the PIMPL idiom does the same thing in just more convoluted but arguably more controlled manner.

What would be the proper/preferred way of doing file reading in a const method without prejudice to const-correctness?


Solution

  • Do not put the file handle object in your class, directly.

    Have your class contain a std::shared_ptr (as opposed to a regular pointer in order to avoid dealing with RAII yourself), which even a const method can use, to read from.

    (You may/may not have to do something in your class's copy constructor and/or assignment operator, in order to get the right semantics for these situations, with respect to the file handle)