hauron hauron - 1 year ago 89
C++ Question

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
manages conversion for related types well, similarly to inheritance. However, is this true that
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
to be for free. Is this
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download