Resource Acquisition Is Initialization

RAII is a Programming should be accessed via classes. This means that the class’s constructor allocates the resources, and its destructor deallocates it.

Here is an example of not using RAII:

RawResourceHandle* handle=createNewResource();
handle->performInvalidOperation();  // Oops, throws exception
deleteResource(handle); // oh dear, never gets called so the resource leaks

Notice that you get a memory leak.

Here is an example using RAII:

class ManagedResourceHandle {
   ManagedResourceHandle(RawResourceHandle* rawHandle_) : rawHandle(rawHandle_) {};
   ~ManagedResourceHandle() {delete rawHandle; }
   ... // omitted operator*, etc
   RawResourceHandle* rawHandle;

ManagedResourceHandle handle(createNewResource());

Notice that if an exception is thrown, the resource is still deallocated. This makes it memory safe.

What’s more, when the object leaves scope, the resource is automatically deallocated.

Referenced By