Since C++11, because of several reasons, developers tend to use smart pointer classes for dynamic lifetime objects. And with those new smart pointer classes, standards, even suggest to not use operators like new
instead they suggest to use make_shared
or make_unique
to avoid some error prone.
If we like to use a smart pointer class, like shared_ptr
, we can construct one like,
shared_ptr<int> p(new int(12));
Also we would like to pass a custom deleter to smart pointer classes,
shared_ptr<int> p(new int(12), deleter);
On the other hand, if we like to use make_shared
to allocate, for ex. int
, instead of use new
and shared_ptr
constructor, like on the first expression above, we can use
auto ip = make_shared<int>(12);
But what if we like to also pass a custom deleter to make_shared
, is there a right way to do that? Seems like compilers, at least gcc, gives an error to,
auto ip = make_shared<int>(12, deleter);
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.