Search code examples
c++heap-memoryshared-ptrstack-memory

shared_ptr creation after object creation


Is there a difference between:

Foo *foo = new Foo();
shared_ptr<Foo> sp(foo);
_fooVector.push_back(sp);

and

shared_ptr<Foo> sp(new Foo());
_fooVector.push_back(sp);

according to stack and heap. In all examples i can find new is used on the same line where the smart pointer get's created. So i'm wondering if the firs example is valid.


Solution

  • First example if valid, but it's more exception-safe and correct to use make_shared.

    shared_ptr<Foo> sp = make_shared<Foo>();
    

    In your first example - you allocate memory, initialize pointer with this memory, create shared_pointer (shared_ptr now owns memory) and then push copy to vector). In second example - you allocate memory, initialize parameter of shared_ptr c-tor with this memory and then as in first example.