Exception safe constructor/destructor
Am I right in that code like this is inherently vulnerable to memory leaks (if the constructor fails)?
Code:
class Foo
{
public:
Foo()
: a(new int), b(new int)
{}
~Foo()
{
delete a;
delete b;
}
private:
int *a;
int *b;
};
If a is assigned memory and then new fails in allocating memory for b, the destructor is never called if I understand this correctly, and thus we have a memory leak (a).
I also understand why destructors should never throw exceptions, but how can you guarantee it if it needs to free up some memory or handle synchronization with an external resource (database etc) that in turn might throw exceptions? The calls to delete in this example might very well fail for some reason making the destructor here not exception safe.