Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "single allocation" mean for boost::make_shared

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?

like image 758
atomd Avatar asked Aug 12 '11 17:08

atomd


People also ask

What is boost :: Make_shared?

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.

Why is Make_shared more efficient?

One reason is because make_shared allocates the reference count together with the object to be managed in the same block of memory.

What does Make_shared return?

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.

How do shared pointers work?

"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.


2 Answers

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:

  1. The object which is being managed
  2. The control block.
like image 101
Steve Jessop Avatar answered Sep 21 '22 22:09

Steve Jessop


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.

like image 27
David Rodríguez - dribeas Avatar answered Sep 21 '22 22:09

David Rodríguez - dribeas