Copy Assignment Operator and Move Assignment Operator in C++

The copy assignment operator and move assignment operator are special member functions in C++ that handle the assignment of one object to another.

If you define a copy/move constructor, remember to always define the corresponding copy/move assignment operator. Otherwise, the code is error-prone.

Code Example

This example demonstrates how to use the copy assignment operator and move assignment operator in C++ to manage object assignments efficiently. It also shows examples of copy constructor and move constructor, which helps to highlight their differences.


Explanation

Copy Constructor

MyClass(const MyClass& a) { // copy constructor
  val = a.val;
  cout << "copy constructor, val = " << this->val << endl;
}

Copy Assignment Operator

MyClass& operator=(const MyClass& a) { // copy assignment operator
  val = -a.val;
  cout << "copy assignment operator, val = " << this->val << endl;
  return *this;
}

Move Constructor

MyClass(MyClass&& a) {
  val = a.val;
  cout << "move constructor, val = " << this->val << endl;
}

Move Assignment Operator

MyClass& operator=(MyClass&& a) {
  val = -a.val;
  cout << "move assignment operator, val = " << this->val << endl;
  return *this;
}

main function

int main() {
  MyClass m1; // default constructor
  MyClass m2 = m1; // copy constructor
  MyClass m3; // default constructor
  m3 = m1; // copy assignment operator
  MyClass m4 = move(m1); // move constructor
  MyClass m5; // default constructor
  m5 = move(m4); // move assignment operator
  return 0;
}
int main() {
    MyClass m1; // default constructor
    MyClass m2 = m1; // copy constructor
    MyClass m3; // default constructor
    m3 = m1; // copy assignment operator
    MyClass m4 = move(m1); // move constructor
    MyClass m5; // default constructor
    m5 = move(m4); // move assignment operator
    return 0;
  }
  

Conclusion

Understanding the copy assignment operator and move assignment operator is essential for efficient object management and resource handling in C++. These operators help ensure that objects are assigned correctly, preventing resource leaks and unnecessary copies.