0
\$\begingroup\$

If you want to use a custom deleter in unique_ptr you either have to pass a functor or the signature of a delete function as template argument. If you have a freestanding delete function (often from a C API) you have to pass the actual address of the function to every instance of your unique_ptr. To avoid that I created a little template that converts a freestanding delete function into a functor.

template<auto* FN>
struct Deleter;

template<typename Ptr, void(*FN)(Ptr*)>
struct Deleter<FN>
{
    void operator()(Ptr* ptr)
    {
        FN(ptr);
    }
};

Usage:

#include <memory>

// Delete function
void delete_float(const float* ptr)
{
    delete ptr;
}

int main()
{
    // How you normally specify a deleter
    std::unique_ptr<float, decltype(&delete_float)> float_ptr1(new float(3.141), &delete_float);

    // With the helper template
    std::unique_ptr<float, Deleter<&delete_float>> float_ptr2(new float(3.141));
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Also it might be helpful to point out the original problem you want to solve with this. \$\endgroup\$ – πάντα ῥεῖ Jul 4 at 17:47
  • \$\begingroup\$ There is no need for a new type, just use std::integral_constant like here. \$\endgroup\$ – Deduplicator Jul 5 at 7:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.