Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 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.

share|improve this answer
    
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 –  gnat Mar 26 '14 at 15:00

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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