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

any difference in constructing shared pointer


what is difference between

auto sp = std::make_shared<Foo>();

auto sp(std::make_shared<Foo>());

Detailed explanation is needed.


Solution

  • For this particular case, there is zero difference. The two declarations are fully equivalent.


    Now to add a bit more context (assume T and U are types).

    The most general case is this:

    U makeU();
    
    T direct(makeU());
    T copy = makeU();
    

    In this case, the first line is direct initialisation. T needs a constructor which accepts a U or something to which U can implicitly convert.

    The second line is copy initialisation. The compiler conceptually rewrites it to mean this:

    T copy(T(makeU()))
    

    That is, a temporary T is initialised from the U object, and then that temporary T is moved (or copied) into copy. This means that T needs the same constructor as for direct, plus an accessible non-explicit copy or move constructor.

    A slightly more specialised case happens when U is T:

    T makeT();
    
    T direct(makeT());
    T copy = makeT();
    

    In this case, these two are almost equivalent. Both use the copy/move constructor to initialise the declared T from the temporary T returned by makeT. The only difference is that direct will work even if its copy/move constructor is declared explicit, while copy will error out in such case.

    When you replace T with auto in the variable declarations, you get your original case. And since the copy and move constructors of std::shared_ptr are not marked explicit, the two lines are fully equivalent.