Sobes.tech
Junior — Middle

Can you explain the purpose and operation of the make_shared function in C++ and how it compares to using new for creating smart pointers?

sobes.tech AI

Answer from AI

The make_shared function in C++ is used to create an object and a std::shared_ptr smart pointer to that object simultaneously. It allocates memory once for both the object and the control block, which improves efficiency.

Advantages of make_shared compared to using new and the shared_ptr constructor directly:

  • Memory allocation optimization: make_shared allocates a single memory block for the object and control block, whereas using new and shared_ptr allocates two separate blocks.
  • Safety: make_shared prevents memory leaks if the shared_ptr constructor throws an exception after new.
  • Convenience: The code becomes shorter and cleaner.

Example:

#include <memory>

std::shared_ptr<int> p1 = std::make_shared<int>(42); // Creates an int object with value 42

// Similarly, but less efficiently:
std::shared_ptr<int> p2(new int(42));

It is recommended to use make_shared in most cases for creating shared_ptr.