Efficiency of std::make_shared
While designing a shared pointer from a raw pointer using the std::make_shared function, there's a difference in efficiency when compared to directly creating a std::shared_ptr using a constructor. Here's a step-by-step explanation:
std::make_shared:
Direct std::shared_ptr Constructor:
As you can see, std::make_shared performs a single allocation (for both the control block and the object), while the direct constructor method performs two allocations (one for the object, another for the control block). This difference in allocations leads to greater efficiency when using std::make_shared.
Exception-Safety
Before C 17, using std::make_shared was also more exception-safe. Consider the following code:
void f(const std::shared_ptr<Object1>& obj1, const std::shared_ptr<Object2>& obj2) { // ... } int main() { f(std::shared_ptr<Object1>(new Object1()), std::shared_ptr<Object2>(new Object2())); return 0; }
Without std::make_shared, the order of evaluation of the arguments is unspecified, and if the allocation of Object1 fails, the memory for Object2 would be leaked. With std::make_shared, this exception-safety issue is addressed.
Disadvantage of std::make_shared
One potential disadvantage of std::make_shared is that it can prevent early deallocation of the object's memory. Unlike the direct constructor method, std::make_shared creates a single memory block for the control block and the object. This means that the memory for both the object and the control block cannot be deallocated independently. If there are weak pointers pointing to the object, they can keep the control block alive even after the object itself is no longer used, potentially leading to memory retention.
The above is the detailed content of Is `std::make_shared` More Efficient Than Directly Constructing `std::shared_ptr`?. For more information, please follow other related articles on the PHP Chinese website!