2

Is it sane to let a read method on a file object to be const? For example

size_t read(void* buffer,size_t length) const;

The read method does not change the contents of the file, but updates the file pointer which is invisible behind a handle.

2
  • Does it make sense for a file object to be const?
    – user7043
    Commented Aug 28, 2012 at 13:21
  • Yes, since then I can use a temporary file object to load data into memory: Foo bar(File("myfile.txt")); or would it be better to say Foo bar("myfile.txt"); and let the ctor of Foo create the file object?
    – user877329
    Commented Aug 28, 2012 at 13:44

1 Answer 1

1

Although the read method does not change the visible state of its object, it does change the visible state of the external world (the file handle), and so should not be declared const. Here's why.

Marking a method const has two meanings: One to the programmer, and a different one to the compiler.

  • To the programmer, const says this method is idempotent. I can call it as many times as I want and make no changes in the visible state of this object, its collaborators, or the outside world. It has no visible side effects.

  • To the compiler, const means this method makes no changes to the state of this object.

To that end, you mark a method as const if it meets the programmers's definition of having no visible side effects. The compiler's definition of const is merely a tool that the compiler can use to check your claim that the method is idempotent.

The mutable keyword, which you use to tell the compiler that this piece of an object's state can be changed and have no visible side effects, is both a tool used to adapt the compiler's understanding of const to the programmer's definition, and evidence that the two definitions are not the same.

3
  • So a const declared read method have to make sure that the returend buffer is the same for the next call, either by saving the data read internally (nessecary for a general stream) or saving the file pointer, which has to be restored before the method returns.
    – user877329
    Commented Aug 29, 2012 at 9:33
  • @user877329, Correct. But what a strange read method that would be. Commented Aug 29, 2012 at 10:55
  • Yes, but definitely useful if a file header has to be read to see if a specific decoder can be used. Note that different files types have magic numbers of different length.
    – user877329
    Commented Aug 31, 2012 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.