7.4. Local Resource Management

Consider the following function in which resources are acquired at the start of the function, some processing takes place, and then the resources are released at the end of the function. Given our discussion so far, what is wrong with this function?

extern Mutex m; 
void f() 
{ 
   // resource acquisition 
   int *p = new int; 
   m.acquire(); 

   process( p ); 

   // freeing up of resources 
   m.release(); 
   delete p; 
} 

The problem is that we cannot guarantee that the resources acquired at the start of the function are ever released. If process() or a function invoked within process() throws an exception, the two resource-freeing statements following the invocation of process() are never executed. This is not an acceptable implementation ...

Get Essential C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.