Assignment to self
This is easy to overlook, especially if you are in a hurry.
If your class does resource allocation and management, and that includes allocating and deallocating memory that is pointed to by a data member of your class, you must be careful to check if an assignment to self occurs, for example:
x = x;
In that case, operator= is called.
The default operator= provided is a shallow copy and if there is a data member that is a pointer to some memory deleted in the destructor, that will delete the memory pointed to twice.
If you provide your own operator=, you can make the same mistake by not checking for this condition.
X& operator=(const X& that)
if (this != &that)
// Do copying action here
This webpage © 2000-2017 by Bob Swart (aka Dr.Bob - www.drbob42.com). All Rights Reserved.