Delphi Clinic C++Builder Gate Training & Consultancy Delphi Notes Weblog Dr.Bob's Webshop
Dr.Bob's Kylix Kicks
 Borland C++Builder lost+found #4
See Also: C++Builder Papers and Columns

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;
   ...
   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. Therefore:
  X& operator=(const X& that)
  {
    if (this != &that)
    {
      //  Do copying action here
    }
    return *this;
  }


This webpage © 2000-2017 by Bob Swart (aka Dr.Bob - www.drbob42.com). All Rights Reserved.