Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

The make_shared function in C++ creates an object and the corresponding shared_ptr in a single memory allocation, which has its advantages and disadvantages.

Advantages:

  • Memory and performance efficiency: one memory allocation for the object and the control block, reducing the number of allocations.
  • Safety: reduces the risk of memory leaks in exceptions, as the object and control block are created atomically.

Disadvantages:

  • Flexibility: make_shared cannot be used with objects requiring a custom allocator or with custom memory management.
  • Memory: the control block and the object are stored together, which can lead to memory retention if there are cyclic references.

Example usage:

#include <memory>

struct MyStruct {
    int x;
    MyStruct(int val) : x(val) {}
};

int main() {
    auto ptr = std::make_shared<MyStruct>(10);
    // ptr manages the MyStruct object
}

Thus, make_shared is recommended for convenient and efficient creation of shared_ptr, unless there are special requirements for memory allocation.