简体   繁体   中英

What's the cost of conversion from std::unique_ptr<Dervied> to std::unique_ptr<Base>?

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:

  • that is called a lot,
  • can be implemented via above conversion, or in a dirtier way: return std::unique_ptr<Base>(new Derived()); ,
  • performance is king.

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 (ie 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.

What's the cost of conversion from std::unique_ptr<Dervied> to std::unique_ptr<Base> ?

I'd assume conversion from Derived& to Base& to be for free. Is this std::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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM