pepero
pepero

Reputation: 7513

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.

Upvotes: 3

Views: 66

Answers (2)

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.

Upvotes: 5

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42899

Since std::shared_ptr<T> has an accessible, non-explicit copy constructor there no difference what so ever.

If you generate the assembly code you'll see that for both examples the compiler will generate the same assembly.

Example #1 (Copy Initialization):

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

Assembly Code

Example #2 (Direct Initialization):

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

Assembly Code

Upvotes: 3

Related Questions