是唯一的_ptr<派生的>到 unique_ptr<Base>自动上铸? [英] Is unique_ptr<Derived> to unique_ptr<Base> up-casting automatic?

查看:25
本文介绍了是唯一的_ptr<派生的>到 unique_ptr<Base>自动上铸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道派生类 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*(并且满足所有删除器要求).特别是,当 TU 的明确公共基类时.

由于构造函数不是explicit,它作为一个从unique_ptrunique_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 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>.

这篇关于是唯一的_ptr&lt;派生的&gt;到 unique_ptr&lt;Base&gt;自动上铸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆