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
What's the Difference Between Std::Move and Std::Forward
_File_, _Line_, and _Function_ Usage in C++
Differences Between Unique_Ptr and Shared_Ptr
What Is the C++ Iostream Endl Fiasco
Unresolved External Symbol _Imp_Fprintf and _Imp_Iob_Func, Sdl2
Is the Safe-Bool Idiom Obsolete in C++11
Output Unicode to Console Using C++, in Windows
Remove Comments from C/C++ Code
Create an Array When the Size Is a Variable Not a Constant
How to Use a Custom Deleter With a Std::Unique_Ptr Member
How to Get Memory Usage At Runtime Using C++
How to Loop Through a C++ Map of Maps
What C++ Smart Pointer Implementations Are Available
Copying a Polymorphic Object in C++
C++: Print Out Enum Value as Text
What's the Best Way to Iterate Over Two or More Containers Simultaneously