New Age C++

Resource Management in C++

RAII, or "Resource Acquisition Is Initialization", has become a standard C++ coding practice. Here's why.

In my initial column on C++ smart pointers, I mentioned how smart pointers overcame the perception that C++ memory management was error-prone. Today I want to talk about the classic resource-management practice they're based on.

Its name is RAII, or "Resource Acquisition Is Initialization". This is an imaginative, yet misleading acronym. But in spite of its odd name, RAII is very useful.

Developers must responsibly use shared resources. They must ensure that files aren't left open, memory isn't unreleased, connections -- to databases or other services -- don't remain active, critical sections aren't locked, and so on. This is, of course, easier said than done.

To tackle that, C++ creator Bjarne Stroustrup proposed a technique that soon became a standard practice ("idiom") in C++ coding. Given a shared resource, all access to it is encapsulated into a class whose accountability ranges from resource allocation to disposal, including any handling in between.

For example, Listing 1 shows a generic representation of a shared resource called shared_resource.

Every task involving this shared_resource type has an associated function that receives a pointer to shared_resource. Some of these functions throw exceptions. Consequently, developers using this API must ensure that shared_resource is released even if exceptions happened duringits life cycle. That's important, because any exception incorrectly handled may result in leakage. Listing 2 contains definitions for all the functions declared in Listing 1.

Listing 3 shows a program using the API from two functions, alpha and beta, called from main. Each function allocates a resource instance and does something with it; both must take care to successfully deal with potential exceptions. This program produces the output shown in Figure 1.

[Click on image for larger view.]
Figure 1. Non-RAII version output.

Both functions, alpha and beta, release the resource if something goes wrong, re-throwing whatever they received. But if I created more functions like these, I'd have to repeat this error-handling logic at every place. This is error-prone, and only a stress test could detect an omission. If not, the bug will propagate to the production environment, with the consequent scalability issue.

Releasing C++ Developers from Pervasive Resource Management
Listing 4 refactors Listing 3 by interposing a resource_access_object. This resource_access_object, declared and defined in Listing 5, mediates between the main program and the resource API. It applies RAII by tying a shared_resource life cycle to its own.

When a resource_access_object loses scope, its shared_resource is recycled because resource_access_object privately keeps a unique_ptr to such instance. I said in the earlier column that, when a unique_ptr is destroyed, it frees its instance. Should exceptions occur, the disposal of shared_resource is still guaranteed. As soon as the exception is captured in the main program, the stack unwinding destroys all automatic objects created from its try block.

Executing this version produces output like Figure 2.

[Click on image for larger view.]
Figure 2. RAII-version output.

Compare the conciseness of functions alpha and beta in the RAII version (Listing 4) with the original ones (Listing 3).

Since the real meat of this technique is in the destructor rather than the constructor, have proposed renaming this technique "Resource Release Is Finalization".

C#, Java and Resource Management
Managed code isn't exempted from leakage, but RAII can't be implemented there. The reason is that object destruction isn't a deterministic task in C# or Java. Releasing critical shared resources in a destructor can't guarantee immediate availability. This is why the finally block, non-existent and unnecessary in C++, was appended to the managed try-catch.

Beside the finally block, the C# using statement available since version 2.0 can automatically release resources that implement System.IDisposable. Listing 6 illustrates this. Running that code produces:

Inside the using block. Exception to be thrown.

Releasing resource. 

When the using statement finishes, IDisposable.Dispose method is called. Java implemented a similar approach in its latest iteration, version 7, with its try-with-resources block. Like System.IDisposable, Java 7 comes with the interface java.lang.AutoCloseable. Listing 7 is the Java version of Listing 6.

Thus, C# and Java provide these interfaces with specific callback methods to implement with the required release logic. In C++, it suffices with a plain object with a well-defined destructor to handle the cleanup.

There's a caveat, though: C++ destructors must not throw exceptions. That's because it will stop the stack unwinding if the destructor was called as a consequence of a previous exception. For this reason, C++ destructors should handle exceptions without propagation.

Responsible Resource Management with RAII
This article discussed a technique that prevents scalability issues by encapsulating all access to a shared resource into a given class. This class uses its destructor as last resort to release the resource previously reserved.

RAII is extensively used in the Standard Template Library (STL). Containers, smart pointers, mutual exclusion locks and many other standard types leverage this idiom to deliver a resilient service. This technique helped many old C libraries, with lousy error handling, transition to C++.

About the Author

Diego Dagum is a software architect and developer with more than 20 years of experience. He can be reached at [email protected].

comments powered by Disqus


  • What's Next for ASP.NET Core and Blazor

    Since its inception as an intriguing experiment in leveraging WebAssembly to enable dynamic web development with C#, Blazor has evolved into a mature, fully featured framework. Integral to the ASP.NET Core ecosystem, Blazor offers developers a unique combination of server-side rendering and rich client-side interactivity.

  • Nearest Centroid Classification for Numeric Data Using C#

    Here's a complete end-to-end demo of what Dr. James McCaffrey of Microsoft Research says is arguably the simplest possible classification technique.

  • .NET MAUI in VS Code Goes GA

    Visual Studio Code's .NET MAUI workload, which evolves the former Xamarin.Forms mobile-centric framework by adding support for creating desktop applications, has reached general availability.

  • Visual Studio Devs Quick to Sound Off on Automatic Updates: 'Please No'

    A five-year-old Visual Studio feature request for automatic IDE updates is finally getting enacted by Microsoft amid a lot of initial developer pushback, seemingly misplaced.

  • First Official OpenAI Library for .NET Goes Beta

    Although it seems Microsoft and OpenAI have been deeply intertwined partners for a long time, they are only now getting around to releasing an official OpenAI library for .NET developers, joining existing community libraries.

Subscribe on YouTube