Resource problems

There are several resource allocation problem connecting to exception handling. These are mostly the result of the procedural usage of resource allocation and free. One technique to solve the problem is what Stroustrup called: Resource allocation is initialization.


// is this correct?
//
void f()
{
char *ptr = new char[1024];

g(ptr);     // can throw exception
h(ptr);

delete [] ptr;
}


//===========================================

void f()
{
try
{
char *ptr = new char[1024];

g(ptr);
h(ptr);

delete [] ptr;
}
catch(...)
{
delete [] ptr;
throw;  // rethrow original exception
}
}

//===========================================


// Resource allocation is initialization

template <typename T>
class Res
{
public:
Res(int i) : p( new T[i] ) {}
~Res() { delete [] p; }
T* ptr() { return p; }
private:
T* p;
};

void f()
{
Res r(1024);

g(ptr);
h(ptr);
}