0

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?

gnat
20.5k29 gold badges117 silver badges308 bronze badges
asked Mar 26, 2014 at 14:48

2 Answers 2

2

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.

answered Mar 26, 2014 at 14:56
1
  • since cursors are to be used from outside of traversed object, this approach seems to make a perfect sense. Why polluting the internals of a traversed object by an information about state that isn't intended to be used within Commented Mar 26, 2014 at 15:00
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.

answered Mar 26, 2014 at 15:04

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.