Custom Removers for std :: shared_ptrs

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

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

To clarify: I prefer to create generic pointers like this, which does not allow you to set a user remote (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 allows me to meet the deleteter task via an argument:

 auto sp2(new Song, MyDeleterFunc); 

But the second uses new , which AFAIK is not as effective as the highest type of distribution.

Perhaps this is clearer: is it possible to get the benefits of make_shared<> , as well as a custom deleter? Does this mean that you need to write a distributor?

+6
source share
2 answers

You should use new in your case, since the design of std::make_shared , to avoid additional allocation, can only work if std::make_shared can use its own (internal) user deletion to free the combined memory of the object and shared_count .

You must agree that with your own user deletion you cannot optimize the distribution, but you should still use the std::make_shared -like wrapper to encapsulate new for reasons of safe use. This helps to avoid memory leaks in cases where the constructors of the object throw an exception, and someone uses

 template<typename T> void f(const T&, const T&); f( std::shared_ptr<X>(new X), std::shared_ptr<X>(new X) ); // possible leak 

instead

 std::shared_ptr<X> make_X() { return std::shared_ptr<X>(new X); } f( make_X(), make_X() ); // no leak 
+4
source

No, there is no form std :: make_shared that accepts a custom debugger.

If you need to return shared_ptr with user deletion, you will need to take a performance snapshot.

Think about it: if you use make_shared , then it will allocate a large area of ​​memory that can store the reference count and your object together, and a new placement will be called. shared_ptr , returned from make_shared , already has a custom div, which explicitly calls your object destructor, and then frees a larger block of memory.

+7
source

Source: https://habr.com/ru/post/956758/


All Articles