When a C++ destructor is not called

Suppose you’re following the “resource acquisition is initialization” technique where you allocate resources as part of construction. You might write classes like:

class X {
Resource* _resource;
public:
X();
~X();
};

X::X() _resource(0) {
_resource = new Resource();
...
}

X::~X() {
delete _resource;
}

The resource is allocated in the constructor when the object is instantiated and released in the destructor when the object is deleted. This is a very common way of allocating resources in C++; it's clean, elegant, and easy to understand. All is right with the world, right?

Suppose after the resource is allocated there's an exception in the X constructor. Your first instinct is to assume the destructor is called and your resource is freed up. Your first instinct is wrong.

If there's an unhandled exception during construction, the object does not exist, therefore the destructor will never be called. In the above case that assumption would lead to a resource leak each time the constructor failed.

Something like this would work better:

X::X() : _resource(0) {
try {
_resource = new Resource();
...
}
catch(...) {
delete _resource;
throw;
}
}

X::~X() {
delete _resource;
}
Tagged with: , ,
Posted in Uncategorized
Design a site like this with WordPress.com
Get started