Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of non constant reference from a constant reference

Tags:

c++

reference

int main(){   
  int x = 10;
  const int&z = x;
  int &y = z; // why is this ill formed?
}

Why is initializing non constant reference to int to a constant reference not correct? What is the reason behind this?

like image 930
Rafael Nadal Avatar asked Dec 16 '22 13:12

Rafael Nadal


1 Answers

Well, why shouldn't it be ill-formed?

It is ill-formed because it breaks the obvious rules of const correctenss. In C++ language you are not allowed to implicitly convert the constant access pass to a non-constant access path. It is the same for pointers and for references. That's the whole purpose of having constant access paths: to prevent modification of the object the path leads to. Once you made it constant, you are not allowed to go back to non-constant, unless you make a specific explicit and conscious effort to do that by using const_cast.

In this particular case you can easily remove the constness from the access path by using const_cast (this is what const_cast is for) and legally modify the referenced object, since the referenced object is not really constant

int main(){   
  int x = 10;
  const int &z = x;
  int &y = const_cast<int &>(z);
  y = 42; // modifies x
}
like image 76
AnT Avatar answered May 12 '23 22:05

AnT