14

I want to know how mutable affects a container (map, vector, list, ...). In addition, what do I have to bear in mind?

Christian Rau
  • 45,360
  • 10
  • 108
  • 185
tonnot
  • 435
  • 1
  • 5
  • 17
  • People would write books about the mutable keyword in general, maybe you can narrow it down, with a bit of code showing what this is about in your specific case. – PlasmaHH Oct 27 '11 at 15:14

1 Answers1

13

mutable, like const, is just a compile-time thing. It just allows you to modify that variable in a constant context. At runtime, there is no difference whether you declared the container mutable or not.

class Foo{
  mutable int i;

public:
  void foo() const{
    // constant context, but you can modify `i`
    i = 5;
  }
};
Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68
Xeo
  • 129,499
  • 52
  • 291
  • 397
  • 2
    It can also be used as a hint for the optimizer – Daniel Oct 27 '11 at 15:17
  • 5
    It does affect what the optimizer can do. – R. Martinho Fernandes Oct 27 '11 at 15:19
  • 1
    There are (at the very least in theory) some optimisation opportunities you can do on immutable objects (in the broadest sense), which might break your code if applied to `const` objects with `mutable` members. However, I'm not familiar enough with compiler implementations to tell to what extent they are implemented. Still, the question is valid for precisely this reason. – bitmask Oct 27 '11 at 15:30
  • @bitmask: That, I don't know. I can only state what I myself know, and that's what I did in this answer. :) – Xeo Oct 27 '11 at 15:31
  • @bitmask: I would scourge a compiler which applied `const` optimizations to an object with `mutable` elements. The compiler knows the definition when deciding on this optimization (typically, using a ROM section) and thus should this detail into account. – Matthieu M. Oct 27 '11 at 15:39
  • 1
    My understanding is that in general const (and therefore its opposite, mutable) can't be used to enable additional optimizations, because the compiler has to account for the fact that somewhere someone might be casting away const anyway. – Jeremy Friesner Oct 27 '11 at 16:01
  • @Jeremy : You're saying the compiler would go out of its way to play nice with code that invokes undefined behavior? Somehow I doubt that... – ildjarn Oct 27 '11 at 17:44
  • 2
    @ildjam You're right, I was misremembering the reasons why const doesn't generally help the compiler optimize. The actual reasons why it doesn't help are here: http://www.gotw.ca/gotw/081.htm – Jeremy Friesner Oct 27 '11 at 18:32