I’ve been searching for the different uses of the keyword mutable
. I’ve found that it is generally used for caching, lazy computing, mutex, …
But I’m wondering if it is coherent to use it for a cursor on a readonly object.
For example, I have a sound class, and I want each sound to be able to keep track of a play cursor, for play/pause use, but I don’t think this is part of the state of the sound.
A const sound cannot be modified, but it can be read.
Is it ok to make the cursor attribute mutable?
I believe your design would be better if the cursor attribute was changed to a function that created and returned a new cursor object that referenced this sound object.
That way you can have multiple modifiable cursors referencing the same sound object, all the cursors at different positions in the sound file -> which is just how cursors should work.
1
Is it ok to make the cursor attribute mutable ?
No. const
is a promise that calling methods on the object won’t change its state in an observable way. I use the term observable loosely here; it doesn’t need to be observable from within the program. If a Sound
object remembers its position in the playback, it has observable mutable state, because calling play()
twice can result in different parts of the song being played. The rest of your program may not be able to observe that through the Sound
class’s public interface, but you can.
mutable
is usually used for caching/lazy evaluation/memoization because you’re going to be returning the same results every time. So even though something inside the object is changing, there’s no way to observe that short of actually looking at the bytes in memory.
That said, do follow Ptolemy’s advice – keeping the cursor out of the object is a cleaner design.