dynamic_cast一个右值引用unique_ptr? [英] dynamic_cast a rvalue-reference unique_ptr?

查看:70
本文介绍了dynamic_cast一个右值引用unique_ptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 Base 和一个派生类 Derived .函数从文件描述符读取对象并返回 Base 对象:

I have a class Base and a derived class Derived. A function reads objects from a file descriptor and returns Base objects:

std::unique_ptr<Base> readNextThing();

在某些地方,我需要将此函数的返回值向下转换为Derived.这很相关,因为输入的unique_ptr是一个右值引用,因此我们不复制指针,而是将其移动.在这种特定的情况下,如果它不是 Derived 子类型的对象,我不介意被销毁,我只需要检测这种情况下向下指针是否为空即可.

And in some place I need to downcast the return value of this function to Derived. This is relevant since the input unique_ptr is a rvalue-reference, so we don't copy the pointer, but move it. In this specific context I don't mind the object being destroyed if it's not of Derived subtype, I just need to detect that the downcast pointer is null in that case.

我可以做到:

template<typename T, typename U>
std::unique_ptr<T> dynamic_unique_cast(std::unique_ptr<U> && unique)
{
    T * t = dynamic_cast<T*>(unique.get());
    if(t) { unique.release(); }  //Transfer ownership
    return std::unique_ptr<T>(t);
}

std::unique_ptr<Derived> d = dynamic_unique_cast<Derived>(readNextThing());

  1. 有内置的功能吗?
  2. 如果发生异常,上述代码中是否存在内存泄漏的风险?

推荐答案

不幸的是 std :: dynamic_pointer_cast

Unfortunately std::dynamic_pointer_cast doesn't work on unique_ptr - there's no reason it couldn't work on an rvalue unique_ptr, except that perhaps the behavior in failure case would be non-obvious.

如果这是一次性案例,则可以通过 std :: shared_ptr 进行操作,请注意它具有来自 unique_ptr :

If this is a one-off case, you could go via std::shared_ptr, noting that it has an implicit constructor from unique_ptr:

auto ptr = std::unique_ptr<Derived>(
    std::dynamic_pointer_cast<Derived>(readNextThing()).release());

但是我认为您建议的实用程序功能更清晰.也许使用此解决方案中的一个?

But I think your proposed utility function is clearer. Perhaps use the one from this solution?

这篇关于dynamic_cast一个右值引用unique_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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