Sobes.tech
Junior — Middle

What are the advantages and disadvantages of using the make_shared function in C++?

sobes.tech AI

Answer from AI

The make_shared function in C++ creates an object and a managed pointer (std::shared_ptr) to it in a single operation.

Advantages:

  • Memory efficiency: One memory block is allocated for both the object and the control block, reducing the number of allocations.
  • Safety: It prevents memory leaks in case of exceptions, as the object is created and wrapped in shared_ptr atomically.
  • Convenience: The code becomes shorter and cleaner.

Disadvantages:

  • Flexibility: It cannot be used with custom allocators or to create shared_ptr with a custom deleter directly through make_shared.
  • Memory: If the object is very large, combining it with the control block may lead to inefficient memory usage.

Example:

#include <memory>

auto ptr = std::make_shared<int>(42);

Here, a shared_ptr to an integer object with the value 42 is created.