When should I use `shared_ptr` make_shared`?
As pointed out in the answers to Difference in make_shared and normal shared_ptr in C ++ is make_shared
superior shared_ptr
in most cases.
Then why does the C ++ standard define both shared_ptr
and make_shared
together? Are there times when I prefer shared_ptr
before make_shared
or even when I can only use shared_ptr
but not make_shared
?
source to share
One situation is that std :: make_shared does not support specifying a custom deleter.
Unlike constructors, it
std::shared_ptr
std::make_shared
does not enable a custom debugger.
You can only do this with the std :: shared_ptr constructor like
std::shared_ptr<Foo> sh5(new Foo, [](auto p) {
std::cout << "Call delete from lambda...\n";
delete p;
});
Another problem is related to the explanation of the associated message, std::make_shared
does only one allocation for both the control unit and the object it points to. This means that after the object is destroyed, the memory it occupied cannot be immediately released. This can cause problems with memory usage.
source to share