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

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube