Why must shared_ptr<> allocate for the control block and managed object separately?

こ雲淡風輕ζ 提交于 2020-01-13 12:16:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!