fenbf / cppstories-discussions

4 stars 1 forks source link

2016/10/wrapping-resource-handles-in-smart/ #59

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Wrapping Resource Handles in Smart Pointers - C++ Stories

Some time ago I covered how to use custom deleters with smart pointers. The basic idea is to specify a dedicated method that will be called when a pointer is released. One logical application of custom deleters might be resource handles like files or the WinApi HANDLE type. Let’s see how can we implement such thing.

https://www.cppstories.com/2016/10/wrapping-resource-handles-in-smart/

lukaszrachwalski commented 3 years ago

Hi Bartek, let's have a look at the case for standard fopen()/fclose() functions. Here, instead of writing extra deleter function you can use just fclose() like this:

std::unique_ptr<FILE, int(*)(FILE*)> f(fopen("file","rb"), &fclose);

or simpler with decltype

std::unique_ptr<FILE, decltype(&fclose)> f(fopen("file","rb"), &fclose);

In std::unique_ptr you don't need to worry about calling fclose() with nullptr. It will not happen because ISO guarantees it. The situation is different with std::shared_ptr where deleter is called for nullptr too, so if you pass nullptr to fclose() function you will get segmentation fault. This approach can be widely used to C APIs.

fenbf commented 3 years ago

thanks, @lukaszrachwalski ! yep, it works as expected. However, if you want to get a smaller size for unique_ptr and don't spare one pointer for deleted it's best to wrap them in stateless function objects.