Let\'s say we have a test.cpp
as follows:
class A;
class B
{
private:
A mutable& _a;
};
Compilation:
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;
};
This could blow your mind away, but a reference is never mutable (can't be made to refer to another object) and the referenced value is always mutable (unless you have a reference-to-const):
#include <iostream>
struct A
{
int& i;
A(int& n): i(n) {}
void inc() const
{
++i;
}
};
int main()
{
int n = 0;
const A a(n);
a.inc();
std::cout << n << '\n';
}
A const method means that a top-level const-qualifier gets added to the members. For a reference this does nothing (= int & const a;
), for a pointer it makes the pointer, not the pointee const (= int* const p
, not const int* p;
).
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.
According to the standard: [7.1.1 para 8]:
"The mutable specifier can be applied only to names of class data members (9.2) and cannot be applied to names declared const or static, and cannot be applied to reference members."
So it's just illegal.