How to Use a Custom Deleter With a Std::Unique_Ptr Member

How do I use a custom deleter with a std::unique_ptr member?

Assuming that create and destroy are free functions (which seems to be the case from the OP's code snippet) with the following signatures:

Bar* create();
void destroy(Bar*);

You can write your class Foo like this

class Foo {

std::unique_ptr<Bar, void(*)(Bar*)> ptr_;

// ...

public:

Foo() : ptr_(create(), destroy) { /* ... */ }

// ...
};

Notice that you don't need to write any lambda or custom deleter here because destroy is already a deleter.

using custom deleter with unique_ptr

Should be

unique_ptr<FILE, int(*)(FILE*)>(fopen("file.txt", "rt"), &fclose);

since http://en.cppreference.com/w/cpp/memory/unique_ptr

or, since you use C++11, you can use decltype

std::unique_ptr<FILE, decltype(&fclose)>

How do you create a custom deleter for a unique_ptr class member that wraps a c function which requires 2 arguments?

Store the fz_context * in the deleter, and pass an instance of that deleter to the unique_ptr that holds the fz_page *

struct PageDeleter
{
explicit PageDeleter(fz_context *ctx)
: ctx(ctx)
{}
void operator()(fz_page* page) const
{
fz_drop_page(ctx, page);
}
fz_context *ctx;
};

Construct the unique_ptr as

fz_context *ctx = // get the fz_context
fz_page *page = // get the fz_page

PageDeleter page_del(ctx);
std::unique_ptr<fz_page, PageDeleter> pagePtr(page, page_del);

You could wrap all of this in a make_unique_fz_page function for convenience.

std::unique_ptr custom deleter that takes two arguments

The deleter is an object. It can hold onto the size.

struct LegacyDeleter
{
int size;
void operator()(char** ptr) const noexcept
{ legacyDeallocate(ptr, size); }
};
using legacy_ptr = std::unique_ptr<char*, LegacyDeleter>;

int main()
{
legacy_ptr ptr(legacyAllocatorFunction(5), LegacyDeleter{5});
}


Related Topics



Leave a reply



Submit