Can std::make_unique be used with abstract interface?
Yes, you can of course use make_unique
for that, but it's not as useful as you might want. You have these options:
std::unique_ptr<IGpsSource> source1 = std::make_unique<GpsDevice>(comPort, baudrate);
auto source2 = std::unique_ptr<IGpsSource>{ std::make_unique<GpsLog>(filename) };
I would say the real question is "why do you want that?"
Unlike
make_shared
,make_unique
has no allocation benefits overnew
. So if you need control of the pointer's type, what you're doing is just fine.Why do you need the pointer to be typed to
IGpsSource
in the first place? An implicit conversion fromstd::unique_ptr<Derived>
rvalues tostd::unique_ptr<Base>
rvalues exists. So if you're actually callingmake_unique
to initialise anIGpsSource
pointer, it will work just fine. And if you want to transfer the pointer somewhere, you'll have tostd::move
it anyway, at which point the conversion can happen again.
std::unique_ptr<Base> base_ptr = std::make_unique<Derived>();
As Angew said, the above should work fine. Provided Derived
uses public inheritance. Just wanted to add that for completeness.