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.
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
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.