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

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

  • What's New for Python, Java in Visual Studio Code

    Microsoft announced March 2024 updates to its Python and Java extensions for Visual Studio Code, the open source-based, cross-platform code editor that has repeatedly been named the No. 1 tool in major development surveys.

Subscribe on YouTube