Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom deleters for std::shared_ptrs

Is it possible to use a custom deleter after creating a std::shared_ptr without using new?

My problem is that object creation is handled by a factory class and its constructors & destructors are protected, which gives a compile error, and I don't want to use new because of its drawbacks.

To elaborate: I prefer to create shared pointers like this, which doesn't let you set a custom deleter (I think):

auto sp1 = make_shared<Song>(L"The Beatles", L"Im Happy Just to Dance With You");

Or I can create them like this, which does let met set a deleter through an argument:

auto sp2(new Song, MyDeleterFunc);

But the second one uses new, which AFAIK isn't as efficient as the top sort of allocation.

Maybe this is clearer: is it possible to get the benefits of make_shared<> as well as a custom deleter? Would that mean having to write an allocator?

like image 686
Kristian D'Amato Avatar asked Oct 25 '13 21:10

Kristian D'Amato


1 Answers

No, there is no form of std::make_shared that takes a custom deleter.

If you need to return a shared_ptr with a custom deleter then you'll have to take the performance hit.

Think about it: If you use make_shared then it will allocate a larger memory region that can store the reference count and your object together, and the placement new will be called. The shared_ptr returned from make_shared already has a custom deleter, one that calls your object's destructor explicitly and then frees the larger memory block.

like image 104
Fozi Avatar answered Oct 21 '22 06:10

Fozi