Understanding the difference in efficiency between std::make_shared and directly constructing a std::shared_ptr can be a perplexing task. Here, we delve into a detailed comparison to elucidate the intricacies of each method.
Consider the following code snippets:
std::shared_ptr<Object> p1 = std::make_shared<Object>("foo"); std::shared_ptr<Object> p2(new Object("foo"));
Direct std::shared_ptr Construction:
std::make_shared Usage:
The key difference lies in the number of heap allocations required:
This singular allocation in make_shared eliminates the need for an explicit new call, resulting in increased efficiency.
Pre-C 17:
Exception handling could previously wreak havoc, as the raw pointer might not have been safely passed to the shared_ptr constructor.
C 17 and Later:
This issue has been resolved thanks to changes in function argument evaluation order. Today, exceptions are handled gracefully, ensuring memory integrity.
As Casey pointed out, a potential disadvantage stems from the single allocation:
The above is the detailed content of `std::make_shared` vs. `std::shared_ptr`: Which is More Efficient?. For more information, please follow other related articles on the PHP Chinese website!