To understand the efficiency of std::make_shared compared to a standard shared_ptr, let's examine their construction processes step by step.
Using the standard shared_ptr constructor:
std::shared_ptr<Object> p2(new Object("foo"));
Using std::make_shared:
std::shared_ptr<Object> p1 = std::make_shared<Object>("foo");
In the standard shared_ptr constructor approach, if an exception is thrown during the construction of Object, no cleanup is performed, leaving dangling memory. However, std::make_shared guarantees that the constructed Object and control block are part of a single allocation and will be cleaned up if an exception is thrown.
The above is the detailed content of `make_shared` vs. `shared_ptr`: Why is One More Efficient and Exception-Safe?. For more information, please follow other related articles on the PHP Chinese website!