vendredi 26 août 2016

Using RAII to manage resources from a C-style API

Resource Acquisition is Initialization (RAII) is commonly used in C++ to manage the lifetimes of resources which require some manner of cleanup code at the end of their lifetime, from deleteing newed pointers to releasing file handles.

How do I quickly and easily use RAII to manage the lifetime of a resource I acquire from a C-style API?

In my case, I want to use RAII to automatically execute a cleanup function from a C-style API when the variable holding the C-style resource it releases goes out of scope. I don't really need additional resource wrapping beyond that, and I'd like to minimize the code overhead of using RAII here. Is there a simple way to use RAII to manage resources from a C-style API?

How to encapsulate C api into RAII C++ classes? is related, but I don't believe it's a duplicate--that question is regarding more complete encapsulation, while this question is about minimal code to get the benefits of RAII.

Aucun commentaire:

Enregistrer un commentaire