-1

When I try to create a mutable local variable in C++ I get:

error mutable is not allowed

during compilation with Visual Studio.

does C++ have a some kind of Mutable local variable?

is there a better way then const_cost for defining a "non const" local variable that received his value from function that return a const value?

thanks

Aviv A.
  • 697
  • 5
  • 11
  • [learn how to ask](http://stackoverflow.com/help/how-to-ask). [Post a Minimal, Complete, Valid Example](http://stackoverflow.com/help/mcve). – Rakib May 27 '14 at 07:58
  • Are you coming from F# or what? You don't need mutable there in C++... – marcus May 27 '14 at 08:08
  • Why the hell did you edit your question to remove its content?! I rolled it back. – user703016 May 27 '14 at 08:44

3 Answers3

3

Local variables are mutable, unless you explicitly declare them as const. So there is no need for a mutable specifier on local variables. This is true for stand-alone functions and for class member functions, including const member functions.

In a const member function, the "thing" that is const is the instance of the class that is being operated on (the this). The local variables are not themselves const unless you declare them as such.

The only exception is for lambdas. Lambda captured variables are "const by default" because they are members of the capture, and the generated function call operators are const. You need to declare the lambda as mutable to be able to mutate its state. (Ordinary local variables inside the lambda body are mutable like other ordinary local variables though.)

Mat
  • 202,337
  • 40
  • 393
  • 406
3

mutable defines that

a member of a class does not affect the externally visible state of the class.

It helps you maintain const correctness.

A local variable does not represent class state (it has local scope) so mutable does not make sense in that context.

Matt Coubrough
  • 3,739
  • 2
  • 26
  • 40
0

mutable can only be applied to data members. It means that it is permissible to assign to the data member from a const member function. The keyword has no meaning with respect to local variables, and cannot be applied to them.

NPE
  • 486,780
  • 108
  • 951
  • 1,012