简体   繁体   中英

Const ref versus const pointer as a data member for operator= overloading

A class with a 'const int&' data member causes the following compilation error when overloading operator= (compiler is g++):

assignment of read-only location.

When the data member is changed to 'const int*', it is fine.

Why?

#include <iostream>

using namespace std;
class B {
 private:
  const int& ir;
  //const int* ir;

 public:
  B(const int& i) : ir(i) {}
  //B(const int& i) : ir(&i) {}
  B& operator=(B& b) { ir = b.ir; return *this; }
};

g++ error message:

opertostack.cpp:9:31: error: assignment of read-only location ‘((B*)this)->       B::ir’
        B& operator=(B& b) { ir = b.ir; return *this; }
                               ^~

You cannot rebind references. Once they are created, they need to refer to the same object for their entire lifetime.

However, your code has much bigger issues. Let's just remove operator=() so it compiles. We then instantiate a B :

B b(42);

b.ir was bound to the temporary int passed to the constructor. That temporary doesn't exists anymore after the constructor returns. b.ir is now a dangling reference. It refers to an object that does not exist anymore.

A pointer isn't going to help you either. If we change B::ir to be a const int* and switch the commented out code, then the result of instantiating a B as above is now a dangling pointer. It points to a temporary that doesn't exist anymore.

So in both cases, you get undefined behavior when using B::ir .

What you want here is just a normal int member. The constructor parameter doesn't need to be a reference either in this case. An int is just as easy to copy as a reference so you don't gain anything by using a reference parameter. Finally, the assignment operator should take a const reference, so that you can assign from const B objects as well:

class B {
private:
    int ir;

public:
    B(const int& i) : ir(i) {}
    B& operator=(const B& b) { ir = b.ir; return *this; }
};

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