Let's say we have a test.cpp
as follows:
class A; class B { private: A mutable& _a; };
Compilation:
$> gcc test.cpp test.cpp:6:20: error: reference ‘_a’ cannot be declared ‘mutable’ [-fpermissive]
My gcc:
$> gcc --version gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1 Copyright (C) 2011 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Why?
References can only be assigned when constructing an object, and cannot be modified thereafter. Thus making them mutable would have no meaning, which is why the standard disallows it.
Mutable data members are those members whose values can be changed in runtime even if the object is of constant type. It is just opposite to constant. Sometimes logic required to use only one or two data member as a variable and another one as a constant to handle the data.
Once initialized, a reference cannot be changed to refer to another object.
There is no reason to have a reference member mutable. Why? Because const member functions can change the object which is referenced by a class member:
class B { public: B(int var) : n(var) {}; void Set(int val) const { n = val; } //no error void SetMember(int val) const { m = val; } //error assignment of member `B::m' in read-only structure protected: int& n; int m; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With