Search code examples
c++c++11templatescopy-constructorassignment-operator

How to implement a copy constructor / assignment operator for a class that has a self-referential pointer?


I'm not quite sure if it's possible to implement a copy constructor/assignment operator, so that if I wanted this class to be equal to another bags instance, it would replace itself with that instance.

I've already tried the general assignment operator implementation (checking for self-referencing etc.).

template <typename T>
class bags {
public:
  bags(const bag<T>& b) {

  }

  bags<T>& operator=(bags<T> const &b) {

  }

  private:
  bags<T> * self;
}

template <typename T>
class apples : public bags<T> {
public:
  void test () {
    self = new bags<T>; // this will invoke assignment operator
  }

private:
  bags<T> * self;
}

Bags is a base class to apples (derived). I expect to be able to have bags contain itself and apples.


Solution

  • There is no need to use

    bags<T> * self;
    

    There is always the language provided this. If you must use self for some reason, make it a member function.

    bags<T> const* self() const
    {
       return this;
    }
    
    bags<T>* self()
    {
       return this;
    }
    

    Another option is to use function local variables.

    bags<T> const* self = this;  // In const member functions.
    bags<T>* self = this;        // In non-const member functions.