9

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?

chwarr
  • 6,777
  • 1
  • 30
  • 57
atomd
  • 558
  • 1
  • 5
  • 11

2 Answers2

12

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.
Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
  • The limit in flexibility is that you don't get to choose the allocator for `make_shared`: It's always `std::allocator`. By the way, how do they manage that `T*` is still always at the top of the data structure? – Kerrek SB Sep 22 '11 at 22:13
4

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.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489