[英]Can I assign a const reference to a non-const variable?
Let's say I define the following operator:假设我定义了以下运算符:
const int & operator= (const MyClass &);
Can I use it to make an assignment to a non-const variable?我可以用它来对非常量变量进行赋值吗?
Reading through the comments here , my understanding is that yes, I can (ie I could do things like a=b
even if a is not const
and the compiler wouldn't complailn).阅读此处的评论,我的理解是,是的,我可以(即即使 a 不是const
并且编译器不会抱怨,我也可以做a=b
之类的事情)。
However, when I try the following code:但是,当我尝试以下代码时:
int main()
{
int x = 42;
const int &y = x; // y is a const reference to x
int &z = y;
}
It fails with the following:它失败并显示以下内容:
compilation
execution
main.cpp:9:8: error: binding reference of type 'int' to value of type 'const int' drops 'const' qualifier
int &z = y;
^ ~
1 error generated.
Yes, you can assign a const reference to a non-reference variable.是的,您可以将 const 引用分配给非引用变量。
int x = 42;
const int &y = x; // y is a const reference to x
int w = y; // this works
int z& = y; // this doesn't
You can assign a const reference to a non-reference because the value is copied, meaning that x
won't be modified if w
is modified as w
is a copy of the data.您可以将 const 引用分配给非引用,因为该值已被复制,这意味着如果w
被修改,则x
不会被修改,因为w
是数据的副本。
You cannot assign a const reference to a non-const reference as when you are using a const reference you are giving a guarantee that you won't modify the pointed value.您不能将 const 引用分配给非 const 引用,因为当您使用 const 引用时,您保证不会修改指向的值。 If you would be allowed to assign a const reference to a non-const reference you would break this guarantee.如果您被允许将 const 引用分配给非 const 引用,您将违反此保证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.