简体   繁体   中英

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).

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.

 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.

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. If you would be allowed to assign a const reference to a non-const reference you would break this guarantee.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM