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?
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"
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With