"RAII" and "scope exit" would be good search terms for Google or SO. For example, look at Boost.ScopeExit or the alternatives to it. The idea is that you create a local object and leave it to the destructor to do the cleanup or "finally" code.
Here's an attempt at applying the idiom directly to your example, reduced to the bare minimum (no error checking and stuff like that):
class AutomaticDeleter
{
public:
AutomaticDeleter(int *a) : a(a) {}
~AutomaticDeleter() { delete[] a; }
int *GetWrappedPointer() const { return a; }
private:
int *a;
};
// ...
AutomaticDeleter automatic_deleter(new int[100]);
if (!doSomething1(automatic_deleter.GetWrappedPointer()))
return;
if (!doSomething2(automatic_deleter.GetWrappedPointer()))
return;
if (!doSomething3(automatic_deleter.GetWrappedPointer()))
return;
And of course, I should mention that this is just an example of what you can do, not of what you should do when applying the idiom to a pointer, especially one returned from new[]
. In real life, you'd use std::vector<int>
and be done with it. The idiom has much more interesting and useful applications.