Sobes.tech
Junior — Middle

What are the advantages of using std::make_shared when creating managed objects in C++?

sobes.tech AI

Answer from AI

std::make_shared creates an object and the corresponding std::shared_ptr in a single operation, which provides several advantages:

  • Memory efficiency: a single memory block is allocated for the object and the control block, reducing overhead.
  • Safety: eliminates the risk of memory leaks in case of exceptions, as the object is created and immediately wrapped in a shared_ptr.
  • Convenience: the code becomes shorter and cleaner, without the need to explicitly write the type twice.

Example:

auto ptr = std::make_shared<MyClass>(constructor_arg);

Instead of:

std::shared_ptr<MyClass> ptr(new MyClass(constructor_arg));