In the boost doc of make_shared, it says:
Besides convenience and style, such a function is also exception safe and considerably faster because it can use a single allocation for both the object and its corresponding control block, eliminating a significant portion of shared_ptr's construction overhead.
I don't understand the meaning of "single allocation", what does it mean?
The advantage of boost::make_shared() is that the memory for the object that has to be allocated dynamically and the memory for the reference counter used by the smart pointer internally can be reserved in one chunk.
One reason is because make_shared allocates the reference count together with the object to be managed in the same block of memory.
Description. It constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr that owns and stores a pointer to it.
"Shared pointer is a smart pointer (a C++ object wih overloaded operator*() and operator->()) that keeps a pointer to an object and a pointer to a shared reference count. Every time a copy of the smart pointer is made using the copy constructor, the reference count is incremented.
An "allocation" means a block of memory obtained from a call to an allocator.
Usually, creating a shared_ptr
with the pointer constructor allocates memory for a "control block", which holds the reference count and the deleter. Copies of that shared_ptr
all refer to the same control block, so that they share the reference count. Hence there are two allocations in total - the object itself and the control block created by shared_ptr
.
If you create the object and shared_ptr
together with make_shared
, then only one allocation is made. You can think of this as a single struct with two members:
The shared_ptr
needs to allocate space for the reference count. This means that you will dynamically create your object (one allocation) and pass it to the shared_ptr
that will in turn allocate the count (second allocation). make_shared
performs a single allocation of a big enough size and then constructs in place both the count and the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With