As pointed in answers to Difference in make_shared and normal shared_ptr in C++, make_shared
outperforms shared_ptr
in most cases.
Then why does C++ standard define both shared_ptr
and make_shared
together? Are there any cases at which I should prefer shared_ptr
to make_shared
or even at which I can only use shared_ptr
but not make_shared
?
One of the situations is that std::make_shared does not support the specifying of the custom deleter.
Unlike the
std::shared_ptr
constructors,std::make_shared
does not allow a custom deleter.
You can only do it with the constructor of std::shared_ptr, e.g.
std::shared_ptr<Foo> sh5(new Foo, [](auto p) {
std::cout << "Call delete from lambda...\n";
delete p;
});
Another issue is just as the linked post explained, std::make_shared
performs only one allocation for both the control block and the object pointed to. That means after the object being destroyed, the memory it occupied might not be deallocated immediately. That might cause some memory usage issue.