Object destruction in C++

In the following text, I will distinguish between scoped objects, whose time of destruction is statically determined by their enclosing scope (functions, blocks, classes, expressions), and dynamic objects, whose exact time of destruction is generally not known until runtime. While the destruction semantics of class objects are determined by destructors, the destruction of a scalar … Read more

When should I create a destructor?

UPDATE: This question was the subject of my blog in May of 2015. Thanks for the great question! See the blog for a long list of falsehoods that people commonly believe about finalization. When should I manually create a destructor? Almost never. Typically one only creates a destructor when your class is holding on to … Read more

shared_ptr magic :)

Yes, it is possible to implement shared_ptr that way. Boost does and the C++11 standard also requires this behaviour. As an added flexibility shared_ptr manages more than just a reference counter. A so-called deleter is usually put into the same memory block that also contains the reference counters. But the fun part is that the … Read more

C++: Life span of temporary arguments?

Temporary objects are destroyed at the end of the full expression they’re part of. A full expression is an expression that isn’t a sub-expression of some other expression. Usually this means it ends at the ; (or ) for if, while, switch etc.) denoting the end of the statement. In your example, it’s the end … Read more

If you shouldn’t throw exceptions in a destructor, how do you handle errors in it?

Throwing an exception out of a destructor is dangerous. If another exception is already propagating the application will terminate. #include <iostream> class Bad { public: // Added the noexcept(false) so the code keeps its original meaning. // Post C++11 destructors are by default `noexcept(true)` and // this will (by default) call terminate if an exception … Read more