Sobes.tech
Middle

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

sobes.tech AI

Answer from AI

The difference between creating an object via the shared_ptr constructor and the make_shared function lies in the memory allocation mechanism and efficiency.

  • shared_ptr constructor: Allocates memory for the object and the control block (reference counters) separately.
    #include <memory>
    
    class MyClass {
    public:
        int value;
        MyClass(int v) : value(v) {}
    };
    
    int main() {
        // Memory for MyClass and the control block are allocated separately
        std::shared_ptr<MyClass> ptr1(new MyClass(10));
        return 0;
    }
    
  • make_shared: Allocates memory for the object and the control block in one memory block.
    #include <memory>
    
    class MyClass {
    public:
        int value;
        MyClass(int v) : value(v) {}
    };
    
    int main() {
        // Memory for MyClass and the control block are allocated in one block
        std::shared_ptr<MyClass> ptr2 = std::make_shared<MyClass>(20);
        return 0;
    }
    
Feature shared_ptr constructor make_shared
Memory allocation Object and control block separately Object and control block in one memory block
Number of memory allocation operations Two One
Efficiency Less efficient More efficient (less overhead)
Exception safety Requires caution with new T(...) Exception-safe
Support for arrays Yes (with custom deleter) No (before C++20), yes (with C++20 for shared_ptr<T[]>)

Using make_shared is preferable unless there are specific reasons to use the constructor, as it is more efficient and safer from an exception safety perspective. The constructor may be needed, for example, when creating a shared_ptr from an existing "raw" pointer.