std :: unique_ptr与派生类 [英] std::unique_ptr with derived class

查看:154
本文介绍了std :: unique_ptr与派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于c ++ 11指针的问题。具体来说,如何将基类的唯一指针转换为派生类?

I have a question about the c++11 pointers. Specifically, how do you turn a unique pointer for the base class into the derived class?

class Base
{
public:
   int foo;
}

class Derived : public Base
{
public:
   int bar;
}

...

std::unique_ptr<Base> basePointer(new Derived);
// now, how do I access the bar member?

这应该是可能的,但我不知道如何。每次尝试使用

it should be possible, but I can't figure out how. Every time I try using the

basePointer.get()

我结束了可执行程序崩溃。

I end up with the executable crashing.

感谢提前,任何建议都将不胜感激。 >

Thanks in advance, any advice would be appreciated.

推荐答案

如果它们是多态类型,并且只需要一个指向导出类型的指针,请使用 dynamic_cast

If they are polymorphic types and you only need a pointer to the derived type use dynamic_cast:

Derived *derivedPointer = dynamic_cast<Derived*>(basePointer.get());

如果它们不是多态类型,只需要一个指向导出类型的指针。 static_cast 并希望获得最佳效果:

If they are not polymorphic types only need a pointer to the derived type use static_cast and hope for the best:

Derived *derivedPointer = static_cast<Derived*>(basePointer.get());

如果您需要转换 unique_ptr 多态类型:

If you need to convert a unique_ptr containing a polymorphic type:

Derived *tmp = dynamic_cast<Derived*>(basePointer.get());
std::unique_ptr<Derived> derivedPointer;
if(tmp != nullptr)
{
    basePointer.release();
    derivedPointer.reset(tmp);
}

如果您需要转换 unique_ptr 包含非多态类型:

If you need to convert unique_ptr containing a non-polymorphic type:

std::unique_ptr<Derived>
    derivedPointer(static_cast<Derived*>(basePointer.release()));

这篇关于std :: unique_ptr与派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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