unique_ptr <derived>是unique_ptr <base /> up-casting自动吗?

时间:2016-04-04 11:58:22

标签: c++11 polymorphism c++14 unique-ptr

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

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

或传递给函数作为参数。

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

我的问题是:这种上传是否总是自动的?或者我们是否需要使用dynamic_cast

明确执行它

1 个答案:

答案 0 :(得分:4)

(草案)标准说:

// 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;

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

  

24 备注:此构造函数不应参与重载决策,除非U*可隐式转换为T*D与{{1}的类型相同}}

此评论的效果是default_delete<T>可以从unique_ptr<T>构建,正好unique_ptr<U>可转换为U*(并且满足所有删除者要求)。特别是,当T*T的明确公共基类时。

由于构造函数不是U,因此它用作从explicitunique_ptr<U>的隐式转换器。