This article discusses the memory layouts when creating an object controlled by a shared_ptr
in C++ through two methods: using a raw pointer and via the make_shared
function.
Inside STL: The shared_ptr constructor vs make_shared
By Raymond Chen
From the article:
There are two ways to create a new object that is controlled by a
shared_ptr
.// From a raw pointer auto p = std::shared_ptr<S>(new S()); // Via make_shared auto p = std::make_shared<S>();They result in two different memory layouts.
In the first case, you manually created a new
S
object, and then passed a pointer to it to theshared_ptr
constructor. Theshared_ptr
adopts the raw pointer and creates a control block to monitor its lifetime. When the last shared pointer destructs, theDispose()
method deletes the pointer you passed in.¹ When the last shared or weak pointer destructs, theDelete()
method deletes the control block.
Add a Comment
Comments are closed.