是唯一的_ptr<派生的>到 unique_ptr<Base>自动上铸? [英] Is unique_ptr<Derived> to unique_ptr<Base> up-casting automatic?
问题描述
我知道派生类 unique_ptr
可能发生在多态类型需要基类 unique_ptr
的地方.例如,从函数返回时
unique_ptr 一些函数(){return make_unique(new Derived());}
或作为参数传递给函数.
//获取唯一指针的函数void someOtherFunction(unique_ptr && ptr)//调用这个函数的代码someOtherFunction(std::move(ptrToDerived));
我的问题是:这种向上转换总是自动的吗?还是我们需要使用 dynamic_cast
显式执行它?
(草案)标准说:
//20.8.1.2.1,构造函数...模板<U类,E类>unique_ptr(unique_ptr&& u) noexcept;模板<U类>unique_ptr(auto_ptr<U>&&u) noexcept;
这些是来自 any unique_ptr 的构造函数.该标准通过如下条款进一步限制了它们的使用:
<块引用>24 备注:除非 U*
可隐式转换为 T*
和 D<,否则此构造函数不应参与重载解析/code> 与
default_delete<T>
这句话的效果是 unique_ptr
unique_ptr
构造,恰好 U*
可以转换为 T*
(并且满足所有删除器要求).特别是,当 T
是 U
的明确公共基类时.
由于构造函数不是explicit
,它作为一个从unique_ptr
到unique_ptr
p>
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
?
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 toT*
andD
is the same type asdefault_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>
.
这篇关于是唯一的_ptr<派生的>到 unique_ptr<Base>自动上铸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!