Skip to content

Copy Constructor Self Assignment C++ Program

C++ Tutorial Operator Overloading II self assignment - 2018 site search:

Self Assignment

Why do we need to protect against the self assignment when we do overloading assignment operator?

But before we dig into the reason why, who would do that kind of silly self assignment?

Window w; w = w; // nobody will do this w[i] = w[j]; // this may happen

Anything can happen. When we write a code, we're not supposed to do make any assumption. So, we need to guard against it.

Here is the code without any protection.

class ScrollBar {}; class Window { ScrollBar *sb; public: Window(ScrollBar *s) : sb(s) {} Window() = default; Window& operator=(const Window&); }; Window& Window::operator=(const Window& rhs) { delete sb; sb = new ScrollBar(*; return *this; } int main() { Window w(new ScrollBar); Window w2(w); }

The code shows a typical overloading assignment overloading.
What could be the flaws in the code?

What could happen if *this and rhs is the same Window instance?

If that's the case, the following line is the problem:

delete sb;

We're deleting since *this and rhs are the same object. After deleting the sb, we're trying to access already deleted object of rhs:

sb = new ScrollBar(*;

We do not want to that happen. The immediate solution is this:

if (this == &rhs;) return *this; delete sb; sb = new ScrollBar(*; return *this;

Still there is a problem.

What if an exception is thrown in the copy constructor after we deleted sb. Then, we're end up having a pointer which is pointing to nothing. So, we need a better code:

Window& Window::operator=(const Window& rhs) { if (this == &rhs;) return *this; ScrollBar *sbOld = sb; sb = new ScrollBar(*; delete sbOld; return *this; }

In this way, the Window object can still holding the ScrollBar even in when there is a thrown exception.

Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong

Assignment Operators

What is “self assignment”?

Self assignment is when someone assigns an object to itself. For example,

Obviously no one ever explicitly does a self assignment like the above, but since more than one pointer or reference can point to the same object (aliasing), it is possible to have self assignment without knowing it:

This is only valid for copy assignment. Self-assignment is not valid for move assignment.

Why should I worry about “self assignment”?

If you don’t worry about self assignment, you’ll expose your users to some very subtle bugs that have very subtle and often disastrous symptoms. For example, the following class will cause a complete disaster in the case of self-assignment:

If someone assigns a object to itself, line #1 deletes both and since and are the same object. But line #2 uses , which is no longer a valid object. This will likely cause a major disaster.

The bottom line is that you the author of class are responsible to make sure self-assignment on a object is innocuous. Do not assume that users won’t ever do that to your objects. It is your fault if your object crashes when it gets a self-assignment.

Aside: the above has a second problem: If an exception is thrown while evaluating (e.g., an out-of-memory exception or an exception in ’s copy constructor), will be a dangling pointer — it will point to memory that is no longer valid. This can be solved by allocating the new objects before deleting the old objects.

This is only valid for copy assignment. Self-assignment is not valid for move assignment.

Okay, okay, already; I’ll handle self-assignment. How do I do it?

You should worry about self assignment every time you create a class. This does not mean that you need to add extra code to all your classes: as long as your objects gracefully handle self assignment, it doesn’t matter whether you had to add extra code or not.

We will illustrate the two cases using the assignment operator in the previous FAQ:

  1. If self-assignment can be handled without any extra code, don’t add any extra code. But do add a comment so others will know that your assignment operator gracefully handles self-assignment:

    Example 1a:

    Example 1b:

  2. If you need to add extra code to your assignment operator, here’s a simple and effective technique:

    Or equivalently:

By the way: the goal is not to make self-assignment fast. If you don’t need to explicitly test for self-assignment, for example, if your code works correctly (even if slowly) in the case of self-assignment, then do not put an test in your assignment operator just to make the self-assignment case fast. The reason is simple: self-assignment is almost always rare, so it merely needs to be correct - it does not need to be efficient. Adding the unnecessary statement would make a rare case faster by adding an extra conditional-branch to the normal case, punishing the many to benefit the few.

In this case, however, you should add a comment at the top of your assignment operator indicating that the rest of the code makes self-assignment is benign, and that is why you didn’t explicitly test for it. That way future maintainers will know to make sure self-assignment stays benign, or if not, they will need to add the test.

This is only valid for copy assignment. Self-assignment is not valid for move assignment.

I’m creating a derived class; should my assignment operators call my base class’s assignment operators?

Yes (if you need to define assignment operators in the first place).

If you define your own assignment operators, the compiler will not automatically call your base class’s assignment operators for you. Unless your base class’s assignment operators themselves are broken, you should call them explicitly from your derived class’s assignment operators (again, assuming you create them in the first place).

However if you do not create your own assignment operators, the ones that the compiler create for you will automatically call your base class’s assignment operators.