Initializing a non-permalink from a permalink

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

Why is the initialization of a non-permalink int reference for a permalink incorrect? What is the reason for this?

+4
source share
6 answers

Well, why not look bad?

It is poorly formed because it violates the obvious rules for constant correlation. In C ++, you are not allowed to implicitly convert a constant access pass to an non-constant access path. The same goes for pointers and references. In order for the whole goal to have permanent access paths: to prevent the modification of the object to which the path leads. Once you have made it permanent, you are not allowed to return to inconstancy unless you make a specific explicit and conscious effort to do this using const_cast .

In this particular case, you can easily remove the constant from the access path using const_cast ( const_cast used for this) and legally change the reference object, since the reference object is not really constant

 int main(){ int x = 10; const int &z = x; int &y = const_cast<int &>(z); y = 42; // modifies x } 
+9
source

Since y not const , you could write y = 42 and change z (which is const ) too.

+1
source

Since a constant link cannot be changed, while a standard link.

+1
source

The compiler assumes that the thing referenced by const int is const int, although this is not the case. You cannot refer to a const constant without referring to an int constant, because then you can change the (conditionally) const int through a link.

+1
source

Because the

 int const x = 10; int const& z = x; int& y = z; y = 42; 

will change the constant variable.

0
source

As others say, this would indirectly alter x , which violates the promise of the constant. See http://en.wikipedia.org/wiki/Const_correctness

0
source

All Articles