Date: Mon, 23 Aug 2021 17:31:10 +0100
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.
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.
Received on 2021-08-23 11:31:25