Is _ device unique <Produced> for unique_ptr <Base> automatic casting?

I know that it is possible that the derived class unique_ptr can occur if the polymorphic types require the base class unique_ptr . For example, returning from a function

 unique_ptr<Base> someFunction() { return make_unique<Derived>(new Derived()); } 

or passing a function as an argument.

 // Function taking unique pointer void someOtherFunction(unique_ptr<Base>&& ptr) // Code calling this function someOtherFunction(std::move(ptrToDerived)); 

My question is: is this always an increase? Or do we need to explicitly execute it using dynamic_cast ?

+6
source share
1 answer

The standard (draft) says:

 // 20.8.1.2.1, constructors ... template <class U, class E> unique_ptr(unique_ptr<U, E>&& u) noexcept; template <class U> unique_ptr(auto_ptr<U>&& u) noexcept; 

These are constructors from any unique_ptr. The standard further restricts their use to the following reservations:

24 Notes: This constructor should not be involved in overload resolution if U* implicitly converted to T* and D is the same type as default_delete<T>

The effect of this remark is that unique_ptr<T> is constructive of unique_ptr<U> exactly U* can be converted to T* (and all delay requirements are met). In particular, when T is a single-valued publicly accessible base class U

Since the constructor is not explicit , it serves as an implicit converter from unique_ptr<U> to unique_ptr<T> .

+3
source

All Articles