Question

Taken from: http://herbsutter.com/2013/05/22/gotw-5-solution-overriding-virtual-functions/

Why should we write:

auto pb = unique_ptr<base>{ make_unique<derived>() };

Instead of just:

auto pb = make_unique<derived>();

My only guess is that if we want auto, we need to help it deduce the right type (base here).

If so, then for me this would be really doubtful merit.. to type auto and then type a lot of initialization on the right side of = ..

What am I missing?

Was it helpful?

Solution

Well, the point is that the first option makes pb a unique_ptr<base>, while the second option makes pb a unique_ptr<derived>. Whether both are correct or not in your situation depends on what you have to do with pb - but definitely the two are not equivalent.

If the relevant part of your program needs to work with a unique_ptr<base> (perhaps because later on you are going to let it to point to an instance of a different derived class), then the second solution is simply not viable.

For example:

auto pb = unique_ptr<base>{ make_unique<derived>() };
// ...
pb = make_unique<derived2>(); // This is OK
// ...

Whereas:

auto pb = make_unique<derived>();
// ...
pb = make_unique<derived2>(); // ERROR! "derived2" does not derive from "derived"
// ...

OTHER TIPS

My only guess is that if we want auto, we need to help it deduce the right type (base here).

That's exactly right. Without the conversion, pb would be a pointer to derived which might not be what you want. For example, you couldn't reassign it to own a base or other derived-class object.

If so, then for me this would be really doubtful merit..

I'm inclined to agree. The author notes in a comment that he did it because he likes to use type deduction as much as possible, with explicit conversions where necessary. Time will tell whether that style becomes commonplace.

auto pb = unique_ptr<base>{ make_unique<derived>() };

the above creates a unique_ptr<base> that contains a derived.

auto pb = make_unique<derived>();

the above creates a unique_ptr<derived> that contains a derived.

While replacing the 2nd with the 1st could be acceptable, they actually do different things.

As an aside, searching for make_unique in the linked-to article results in someone answering this very question there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top