How to pass deleter to make_shared?

As other have said, make_shared cannot be used with a custom deleter. But I want to explain why.

Custom deleters exist because you allocated the pointer in some special way, and therefore you need to be able to deallocate it in a correspondingly special way. Well, make_shared allocates the pointer with new. Objects allocated with new should be deallocated with delete. Which the standard deleter dutifully does.

In short, if you can live with the default allocation behavior, you can live with the default deallocation behavior too. And if you can’t live with the default allocation behavior, you should use allocate_shared, which uses the provided allocator to both allocate and deallocate the storage.

Also, make_shared is allowed to (and almost certainly will) allocate the memory for T and the control block for the shared_ptr within the same allocation. This is something that your deleter can’t really know about or deal with. Whereas allocate_shared is capable of handling it, since the allocator you provide can do allocation and deallocation duties.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)