Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why initialize unique_ptr with a make_unique call?

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?

like image 881
Yanko Avatar asked May 27 '13 13:05

Yanko


1 Answers

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"
// ...
like image 109
Andy Prowl Avatar answered Oct 14 '22 14:10

Andy Prowl