How do I use RAII to manage resources programmed using a C-style API?
There is an easy way to use RAII to manage resources from a C-style interface: the standard library's smart pointers, which come in two flavors:
std::unique_ptr for resources with a single owner and the team of
std::shared_ptr and
std::weak_ptr for shared resources. If you're having trouble deciding which your resource is, this FAQ should help you decide. Accessing the raw pointer a smart pointer is managing is as easy as calling its get member function.
If you want simple, scope-based resource management,
std::unique_ptr is an excellent tool for the job. It's designed for minimal overhead, and is easy to set up to use custom destruction logic. So easy, in fact, that you can do it when you declare the resource variable:
#include <memory> // allow use of smart pointers
struct CStyleResource; // c-style resource
// resource lifetime management functions
CStyleResource* acquireResource(const char *, char*, int);
void releaseResource(CStyleResource* resource);
// my code:
std::unique_ptr<CStyleResource, decltype(&releaseResource)>
resource{acquireResource("name", nullptr, 0), releaseResource};
acquireResource executes where you call it, at the start of the variable's lifetime.
releaseResource will execute at the end of the variable's lifetime, usually when it goes out of scope.
You can do much the same with
std::shared_ptr, if you require that brand of resource lifetime instead:
// my code:
std::shared_ptr<CStyleResource>
resource{acquireResource("name", nullptr, 0), releaseResource};
Now, both of these are all well and good, but the standard library has
std::make_unique and
std::make_shared and one of the reasons is further exception-safety.
GotW#56 mentions that the evaluation of arguments to a function are unordered, which means if you have a function that takes your shiny new
std::unique_ptr type and some resource that might throw on construction, supplying that resource to a function call like this:
func(
std::unique_ptr<CStyleResource, decltype(&releaseResource)>{
acquireResource("name", nullptr, 0),
releaseResource},
ThrowsOnConstruction{});
means that the instructions might be ordered like this:
call acquireResource
construct ThrowsOnConstruction
construct std::unique_ptr from resource pointer
Now our precious C interface resource won't be cleaned up properly if step 2 throws because the
unique_ptr hasn't been constructed yet..
Again as mentioned in
GotW #56, there's actually a relatively simple way to deal with the exception safety problem. Unlike expression evaluations in function arguments, function evaluations can't be interleaved. So if we acquire a resource and give it to a
unique_ptr inside a function, we'll be guaranteed no tricky business will happen to leak our resource when
ThrowsOnConstruction throws on construction. We can't use
std::make_unique, because it returns a
std::unique_ptr with a default deleter, and we want our own custom flavor of deleter. We also want to specify our resource acquisition function, since it can't be deduced from the type without additional code. Implementing such a thing is simple enough with the power of templates.
#include <memory> // smart pointers
#include <utility> // std::forward
template <
typename T,
typename Deletion,
typename Acquisition,
typename...Args>
std::unique_ptr<T, Deletion> make_c_handler(
Acquisition acquisition,
Deletion deletion,
Args&&...args){
return {acquisition(std::forward<Args>(args)...), deletion};
}
You can use it like this:
auto resource = make_c_handler<CStyleResource>(
acquireResource, releaseResource, "name", nullptr, 0);
and call func worry-free, like this:
func(
make_c_handler<CStyleResource>(
acquireResource, releaseResource, "name", nullptr, 0),
ThrowsOnConstruction{});
The compiler can't take the construction of
ThrowsOnConstruction and stick it between the call to
acquireResource and the construction of the
unique_ptr, so you're good.