Search This Blog

Tuesday, October 27, 2009

C++, Destructor Review

1. If you don't define one, compiler will generate an "inline default destructor for you."
a. Pimpl problem: solve by declaring a non-inline destructor link, link2
b. Potential code bloat: P.707 C++ Primer, link
2. The destructors for member -- and for base -- are implicitly called from a derived class destructor. It does not matter whether you define one or complier generated one. Therefore, if your class member does not allocate memory on heap, the default destructor is good to free all your member in your class. Otherwise, think about putting delete[] or delete in your own destructor. p.589, Programming Principle and Design.
3. Destructors are guaranteed to be called when
a. going out of scope (assumed the object is completely constructed)
b. you call delete (delete will first free the pointer, and then call the destructor)
"A destructor is NOT invoked when either a reference or a pointer to a class object goes out of scope" p705, c++ primer.
This is why you need to delete the memory when using vector of pinters.
the memory of pointers are deleted, but the memory of pointers point to remain!
4. Destructor can do more than just free memory. Just add logic to destructor
5. Almost always try not to throw exception in the destructor, since it violates RAII, and C++ uses RAII in many many places.
6. Almost always try not to call destructor yourself (unless you use placement new).

No comments: