unique_ptr <Derived>是unique_ptr <Base> up-casting自动吗?

Cha*_*ert 9 polymorphism unique-ptr c++11 c++14

我知道派生类unique_ptr可能发生在unique_ptr多态类型需要基类的地方.例如,从函数返回时

unique_ptr<Base> someFunction()
{
     return make_unique<Derived>(new Derived());
}
Run Code Online (Sandbox Code Playgroud)

或传递给函数作为参数.

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

我的问题是:这种向上转换是否总是自动的?或者我们需要使用明确执行它dynamic_cast吗?

n. *_* m. 7

(草案)标准说:

// 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;
Run Code Online (Sandbox Code Playgroud)

这些是来自任何unique_ptr 的构造函数。该标准通过如下条款进一步限制了它们的使用:

24名备注:此构造不得参与重载解析,除非U*隐式转换为T*和D是类型相同default_delete<T>

这句话的效果是unique_ptr<T>可构造从unique_ptr<U>精确U*可转换为T*(并且满足所有删除器要求)。特别是,whenT是 的明确公共基类U。

由于构造函数不是explicit,因此它充当从unique_ptr<U>to的隐式转换器unique_ptr<T>。