开发者

Initialization of non constant reference from a constant reference

开发者 https://www.devze.com 2023-03-10 19:45 出处:网络
int main(){ int x = 10; const int&z = x; 开发者_StackOverflow社区 int &y = z; // why is this ill formed?
int main(){   
  int x = 10;
  const int&z = x;
 开发者_StackOverflow社区 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?


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
}


Since y isn't const, you would be able to write y = 42 and change z (which is const) too.


Because a const reference is unmodifiable, while a standard reference is.


The compiler assumes that the thing referred to by a const int & is a const int, even though in this case it isn't. You cannot make a non-const reference refer to a const int, because you would then be able to change the (notionally) const int via the reference.


Because

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

y = 42;

would modify a constant variable.


As others say, it would allow one to indirectly change x, which breaks the const-correctness promise. See http://en.wikipedia.org/wiki/Const_correctness

0

精彩评论

暂无评论...
验证码 换一张
取 消