Search code examples
c++c++11shared-ptr

std::shared_ptr initialization


What is the difference between:

std::shared_ptr<int> p1 = std::shared_ptr<int>(new int);

and

std::shared_ptr<int> p2 = (std::shared_ptr<int>) new int;

Which is better and why?


Solution

  • Neither. This one is strictly preferable:

    auto p3 = std::make_shared<int>();
    

    (Although it has slightly different semantics, since it initializes the int object, unlike your code.)

    This version is subexpression-wise correct, doesn't contain the red-flag word "new", and also uses a more efficient allocation scheme.