Sobes.tech
Middle

What is the difference between creating a shared_ptr object using the constructor and using the make_shared function?

sobes.tech AI

Answer from AI

The main difference lies in the amount of memory allocations:

  1. shared_ptr constructor: Requires two separate memory allocations. One for the object itself, and another for the control block, which contains reference counters and other metadata.
  2. make_shared: Performs a single combined memory allocation for both the object and the control block.
Characteristic shared_ptr Constructor make_shared
Number of allocations Two One
Efficiency Less efficient More efficient
Exception guarantees Less (possible leak in expression) More (atomic operation)
Use of dynamic array Possible (std::shared_ptr<T[]>) Not possible (std::make_shared<T[]>)

Example with constructor:

// Allocate memory for MyObject
MyObject* obj = new MyObject();
// Allocate memory for control block
std::shared_ptr<MyObject> ptr_ctor(obj);

Example with make_shared:

// Single allocation for MyObject and control block
std::shared_ptr<MyObject> ptr_make = std::make_shared<MyObject>();

Using make_shared is preferable in most cases due to better performance and exception safety. However, there are scenarios where only the constructor is suitable, such as creating a shared_ptr from an already existing raw pointer or working with custom allocators.