FAQ 31.06 What if an object has a pointer to an allocation and one of the object s member functions delete s the allocation?

FAQ 31.06 What if an object has a pointer to an allocation and one of the object's member functions deletes the allocation?

graphics/new_icon.gif

That member function must immediately restore the integrity of the object holding the pointer.

If some member function (other than the destructor) deletes memory allocated from the heap, then the member function must either reassign the pointer with a previously allocated (new) object or set a flag that tells the destructor to skip the delete. Setting the pointer to NULL can be used as such a flag.

For example, some assignment operators need to delete an old allocation as well as allocate a new one. In such cases, the new allocation should be performed before the old is deleted in case the allocation throws an exception. The goal is for the assignment operator to be atomic: either it should succeed completely (no exceptions, and all states successfully copied from the source object), or it should fail (throw an exception) without changing the state of the this object. It is not always possible to meet the goal of atomicity, but the assignment operator must never leave the this object in an incoherent state.

A related guideline is to use a local auto_ptr<T> to point to the new allocation. This will ensure that the new allocation is deleted if an exception is thrown by some subsequent operation in the member function. The ownership of the allocated object can be transferred to the this object by assigning from the local auto_ptr into the auto_ptr<T> in the this object.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net