Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I declare a reference to a mutable object? ("reference cannot be declared mutable")

Tags:

c++

reference

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?

like image 447
Martin Avatar asked Dec 12 '11 02:12

Martin


People also ask

Are references mutable in C++?

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.

What is mutable C++?

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.

Can reference be changed once initialized?

Once initialized, a reference cannot be changed to refer to another object.


1 Answers

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; }; 
like image 135
Pavel Zhuravlev Avatar answered Sep 16 '22 11:09

Pavel Zhuravlev