C++ Logo

std-proposals

Advanced search

Re: Easier make_unique with deleter function

From: Peter C++ <peter.cpp_at_[hidden]>
Date: Tue, 24 Aug 2021 08:33:24 +0200
Why not write your own RAII wrapper. if putting it into a container is not needed, a simple scoped manager class with suppressed copy/move operations will do.

that might be much less involved than bending unique_ptr to your will. or if you insist on unique_ptr create your own empty custom deleter type.

regardsPeter

Sent from Peter Sommerlad's iPad
+41 79 432 23 32

> On 23 Aug 2021, at 18:32, Phil Endecott via Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> ´╗┐Dear Experts,
>
> I have been contemplating what the easiest current or future
> way to create a unique_ptr with a custom deleter function is.
>
> For example, libtiff has
>
> TIFF* TIFFOpen(args);
> void TIFFClose(TIFF*);
>
> I'd like to be able to write something like:
>
> auto tiffp = make_unique_with_deleter( TIFFOpen(fn), TIFFClose );
>
> Of course it can't be quite that simple. Fundamentally unique_ptr
> stores the deleter only in the type, which I think means the
> deleter function can only ever be a template parameter:
>
> auto tiffp = make_unique_with_deleter<TIFFClose>( TIFFOpen(fn) );
>
> I haven't quite worked out how to implement that yet; I can't
> avoid requiring the pointer type in the template list but I bet
> one of you experts knows how to avoid that:
>
> template <typename T, void(*DEL)(T*)>
> struct wrap_deleter
> {
> void operator()(T* p) const { DEL(p); }
> };
>
> template <typename T, void(*DEL)(T*)>
> auto make_unique_with_deleter(T* raw_ptr)
> {
> return std::unique_ptr<T, wrap_deleter<T,DEL>>(raw_ptr);
> }
>
> auto tiffp = make_unique_with_deleter<TIFF, TIFFClose>( TIFFOpen(fn) );
>
> So anyway:
>
> - Has anything like this been considered before?
> - Can anyone suggest how to avoid needing the type template parameter?
> - Have I missed an existing feature that can convert a function pointer
> value into a functor type, as my wrap_deleter does?
>
>
> Thanks, Phil.
>
>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2021-08-24 01:33:32