In your assignment operator you need to make sure that the assigned to object is cleaned up before overwriting its value by a new value. After all, this left hand side of the assignment already references a value. The easiest way to write an assignment operator is to leverage the existing copy constructor and destructor and use a function swap()
to exchange the two objects:
MyClass& MyClass::operator = (MyClass c) {
this->swap(c);
return *this;
}
void MyClass::swap(MyClass& other) {
std::swap(this->data, other.data);
}
This way the value is already copied in the value c
and the current value is exchanged with the one held by c
. When c
gets destroyed the reference count gets decremented as needed.
Note, that std::share_ptr<T>
already does reference counting using a rather fancy mechanism: you might want to use the standard class rather than rolling your own.