Reputation: 4668
Consider a simple piece of code:
class Base {};
class Derived : public Base {};
std::unique_ptr<Base> foo()
{
return std::make_unique<Derived>();
}
I know std::unique_ptr
manages conversion for related types well, similarly to inheritance. However, is this true that std::unique_ptr<Base>
and std::unique_ptr<Derived>
are in fact unrelated, and the provided code is possible (and works) thanks to conversions rather than inheritance?
If that is the case, this conversion must come with a cost. I'd assume conversion from Derived&
to Base&
to be for free. Is this std::unique_ptr
costing me much?
Note: The question is based on presumption that there exists a function:
return std::unique_ptr<Base>(new Derived());
,Upvotes: 1
Views: 105
Reputation: 126857
The conversion should be essentially free; std::unique_ptr
is just a wrapper around a pointer, and the "conversion" between the pointers stored in std::unique_ptr<Derived>
and std::unique_ptr<Base>
is purely formal (i.e. it happens just in the type system), the actual value is untouched.
This can be easily seen in the generated code, which boils down to copying the pointer and the deleter into the new std::unique_ptr
and zeroing out the pointer in the old one.
Upvotes: 2
Reputation: 30604
What's the cost of conversion from
std::unique_ptr<Dervied>
tostd::unique_ptr<Base>
?I'd assume conversion from
Derived&
toBase&
to be for free. Is thisstd::unique_ptr
costing me much?
Depends on the optimisation levels being applied. But from the OP, you probably have those turned on, so essentially nothing. The pointer conversion is very cheap.
To truly evaluate what the cost is, the binary will need to be checked. See here for a sample of this output;
foo(): # @foo()
pushq %rbx
movq %rdi, %rbx
movl $1, %edi
callq operator new(unsigned long)
movq %rax, (%rbx)
movq %rbx, %rax
popq %rbx
retq
Upvotes: 2