
Custom Deleters for C++ Smart Pointers - ingve
http://www.bfilipek.com/2016/04/custom-deleters-for-c-smart-pointers.html
======
thrownaway2424
This is one of my favorite features of unique_ptr. It is an all-purpose way to
make something happen at the end of scope without having to write a new struct
and destructor. You don't even need the pointer at all since you can simply
do:

    
    
      std::unique_ptr<void> finally(42, [](void* unused){ whatever });

~~~
toth
That is a pretty cool use. In practice though, it is pretty unreadable unless
you wrap it in a macro or template, and if you are doing that you might as
well just implement it yourself. Something like:

    
    
        struct OnScopeExit {
            OnScopeExit(std::function<void()> f) :  f_(f) {};
            ~OnScopeExit() { f_();};
            std::function<void()> f_;
        };
    

Which you'd then use as

    
    
        {
            OnScopeExit x([]() { std::cout << "Exited scope!" << std:endl; };
            // ...
        }

~~~
joebaf
that's the beauty of using destructors to clean things when an object goes out
of scope.

in your OnScopeExit we could use templates (and not use std::function), that
way any callable thing could be called - and it would be lighter than
std::function

~~~
toth
I actually don't think there's a nice way of doing this without making the
interface slightly more annoying. If you make OnScopeExit a template on a
callable, then you need to give it the type of the callable explicitly on
construction, which means that using a lambda becomes more annoying. I.e.,
you'd have to do it like this:

    
    
        auto f = []() { std::cout << "Exited Scope!" << std::endl; };
        OnScopeExit<decltype(f)> x(f);
    

The way unique_ptr does it is by using type erasure, which requires a virtual
function call internally, just like std::function.

~~~
Kristine1975
_> The way unique_ptr does it is by using type erasure, which requires a
virtual function call internally_

That's shared_ptr. unique_ptr does not perform type erasure.

------
stinos
minor nitpicks: please use the constructor's initializer list for
initialization of class members [1] and do not use hungarian notation or forms
thereof with other names which I cannot remember [2]

[1] [http://stackoverflow.com/questions/15679977/constructor-
init...](http://stackoverflow.com/questions/15679977/constructor-
initialization-vs-assignment)

[2]
[http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#...](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rl-
name-type)

