Cătălina Sîrbu
Cătălina Sîrbu

Reputation: 1283

What should a copy assignment do

I am searching for an answer to the following explaination (from the book "A tour of C++")

MyClass& operator=(const MyClass&) // copy asignment: clean up target and copy

I've never cleaned up a target (or at least I don't get what does it mean) when copying so:


Below in the book it states:

MyClass& operator=(MyClass&&) // move assignment: clean up target and move

Here it makes sense to clean up target as this is how I understand the move -ing thing works

Upvotes: 1

Views: 223

Answers (1)

Surt
Surt

Reputation: 16089

Suppose MyClass has an owning pointer

class MyClass {
  Owned *that;
public:
...
  MyClass& operator=(const MyClass&other) // copy asignment: clean up target and copy
  {
     Owned = other->owned;
  }

What happens with the memory that pointed to? it is leaked. So instead do

  MyClass& operator=(const MyClass&other) // copy asignment: clean up target and copy
  {
     if (this == &other)  // prevent self assignment as this would in this case be a waste of time.
       return *this;
     delete that; // clean up
     that = new Owned(*other->that); // copy
     return *this; // return the object, so operations can be chained.
  }

Better thanks to @PaulMcKenzie && @Eljay

  MyClass& operator=(const MyClass&other) // copy asignment: clean up target and copy
  {
     Owned *delayDelete = that;
     that = new Owned(*other->that); // copy, if this throws nothing happened
     delete delayDelete; // clean up
     return *this; // return the object, so operations can be chained.
  }

Upvotes: 2

Related Questions