问题
This linked question asked if the make_shared<>
function and the shared_ptr<>
constructor differ.
What happens when using make_shared
Part of the answer was that make_shared<>
will usually allocate memory for both the pointed to object and smart pointer control block in a single allocation. The shared_ptr<>
constructors use two allocations.
cppreference states that the constructors "must" do so but no reason is given.
Why is this? Is it for some reason impossible? Or is it forbidden by the standard for some other reason?
回答1:
Think about how the std::shared_ptr
constructor works:
std::shared_ptr<Foo>(new Foo());
First the new Foo()
expression is evaluated; ::operator new
allocates memory for the Foo
object and then constructs it. The resulting pointer is passed in as an argument to the std::shared_ptr
constructor.
See the problem? The Foo
allocation has already been performed! The smart pointer constructor has no option to allocate room for both the control block and the object in the same allocation, since it was not responsible for allocating memory for the object.
std::make_shared
, on the other hand, is in charge of both allocations and so it is possible to allocate room for both in one heap allocation, and then placement-new-construct both the object and control block within that one allocation.
来源:https://stackoverflow.com/questions/26351877/why-must-shared-ptr-allocate-for-the-control-block-and-managed-object-separate