Moule Lin
← All notes

Why the Assignment Operator Returns a Reference

If a user-defined class does not overload its = operator, the compiler generates one automatically. However, this compiler-generated overload may be unsafe, because it performs a so-called “shallow copy”: for a pointer, it copies the pointer's value rather than the memory it points to. The memory then has two pointers pointing to it, and the class objects are destructed twice, but the memory can only be freed once, so the second free causes an access error.

  To avoid this “shallow copy” problem, you need to overload the = operator. It is a binary operator, so the function name and parameters are easy to determine; the key point is its return type. Generally, it should return a reference to the class type, so that so-called “chained assignment” works. The question I once had was: why must it return a reference to enable “chaining”? Here I think it through and summarise, starting from the code.

Copy code
class Student
{
public:
Student(const char* name);~Student();
Student& operator=(const Student &student);private:
char *m_name;
};
Copy code
Copy code
//Test code
Student s1(“Lee”);
Student s2(“Diwen”);
Student s3(“Tom”);

//First s2 = s1 is executed, i.e. s2.operator=(s1), which returns a reference to s2
//Then s3 = s2 is executed, i.e. s3.operator=(s2)
s3 = s2 = s1;
Copy code
  Chained = is evaluated from right to left. So the right-hand side certainly has to return an object of type Student. The question is: why return a reference?

  Look at the function that overloads the = operator: its parameter type is a const reference, meaning the argument passed in must be an lvalue. If the return type were Student, it would return an anonymous object (an rvalue); in chained assignment this return value (an rvalue) must in turn be passed in as an argument, which obviously would not work (it doesn't work without const, but does with const).
A const reference can bind to an rvalue, and the overloaded assignment operator returns a reference, of course, to avoid a pointless copy.