Assignment operator - Self-assignment

cpx picture cpx · Apr 10, 2011 · Viewed 7k times · Source

Does the compiler generated assignment operator guard against self assignment?

class T {

   int x;
public:
   T(int X = 0): x(X) {}
};

int main()
{
   T a(1);
   a = a;
}

Do I always need to protect against self-assignment even when the class members aren't of pointer type?

Answer

Johnsyweb picture Johnsyweb · Apr 10, 2011

Does the compiler generated assignment operator guard against self assignment?

No, it does not. It merely performs a member-wise copy, where each member is copied by its own assignment operator (which may also be programmer-declared or compiler-generated).

Do I always need to protect against self-assignment even when the class members aren't of pointer type?

No, you do not if all of your class's attributes (and therefore theirs) are POD-types.

When writing your own assignment operators you may wish to check for self-assignment if you want to future-proof your class, even if they don't contain any pointers, et cetera. Also consider the copy-and-swap idiom.