Is unique_ptr<Derived> to unique_ptr<Base> up-casting automatic?

流过昼夜 提交于 2019-12-30 08:15:41

问题


I know it is possible that a derived class unique_ptr can take place where base class unique_ptr is required for polymorphic types. For example, while returning from function

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

or passing to function as argument.

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

My question is: Is this upcasting always automatic? Or do we need to explicitly perform it using dynamic_cast?


回答1:


The (draft) standard 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;

Those are constructors from any unique_ptr. The standard further restricts their usage by clauses like this:

24 Remarks: This constructor shall not participate in overload resolution unless U* is implicitly convertible to T* and D is the same type as default_delete<T>

The effect of this remark is that unique_ptr<T> is constructible from unique_ptr<U> precisely U* is convertible to T* (and all deleter requirements are met). In particular, when T is an unambiguous public base class of U.

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



来源:https://stackoverflow.com/questions/36401999/is-unique-ptrderived-to-unique-ptrbase-up-casting-automatic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!