是unique_ptr< Derived>到unique_ptr< Base>自动上投? [英] Is unique_ptr<Derived> to unique_ptr<Base> up-casting automatic?
问题描述
我知道派生类unique_ptr
可能发生在多态类型需要基类unique_ptr
的地方.例如,从函数返回时
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));
我的问题是:这种转换总是自动的吗?还是我们需要使用dynamic_cast
明确执行它?
My question is: Is this upcasting always automatic? Or do we need to explicitly perform it using dynamic_cast
?
推荐答案
(草稿)标准说:
// 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;
这些是 any unique_ptr中的构造函数.该标准通过如下子句进一步限制了它们的使用:
Those are constructors from any unique_ptr. The standard further restricts their usage by clauses like this:
24 备注:该构造函数不得参与重载解析,除非
U*
可隐式转换为T*
并且D
与default_delete<T>
24 Remarks: This constructor shall not participate in overload resolution unless
U*
is implicitly convertible toT*
andD
is the same type asdefault_delete<T>
此注释的作用是,unique_ptr<T>
可以从unique_ptr<U>
构造,而U*
可以转换为T*
(并且满足所有删除器要求).特别是当T
是U
的明确公共基类时.
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
.
由于构造函数不是explicit
,因此它用作从unique_ptr<U>
到unique_ptr<T>
的隐式转换器.
Since the constructor is not explicit
, it serves as an implicit converter from unique_ptr<U>
to unique_ptr<T>
.
这篇关于是unique_ptr< Derived>到unique_ptr< Base>自动上投?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!