What is the difference between std::make_shared<T> and std::shared_ptr<T>(new T) in terms of heap allocations and exception safety?
Last updated
make_shared<T>does one heap allocation for object + control block (better locality).shared_ptr<T>(new T)does two.With separate
new, a call likef(shared_ptr<T>(new T), g())can leak ifg()throws before the owner is built.make_sharedhas no unmanaged window.Trade-off: with
make_sharedthe object's memory isn't freed until allweak_ptrs die, and it can't take a custom deleter.