加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – boost :: shared_ptr和继承

发布时间:2020-12-16 05:19:08 所属栏目:百科 来源:网络整理
导读:我正面临着一种情况,我有一个std :: vector的boost :: shared_ptrs的基类.在我的程序过程中,我需要将共享指针存储在该向量中的派生类对象中,并且在稍后的程序中,需要检索这些共享指针. 以下代码说明了我的问题: #include iostream#include vectorusing name
我正面临着一种情况,我有一个std :: vector的boost :: shared_ptrs的基类.在我的程序过程中,我需要将共享指针存储在该向量中的派生类对象中,并且在稍后的程序中,需要检索这些共享指针.

以下代码说明了我的问题:

#include <iostream>
#include <vector>
using namespace std;

#include <boost/make_shared.hpp>
#include <boost/foreach.hpp>

class Base
{
public:
    virtual ~Base()
    {
    }
};
/******************************************/

typedef boost::shared_ptr< Base > BasePtr;
/******************************************/

class Derived1 : public Base
{
public:
    void derived1_test()
    {
        cout << "derived1_test" << endl;
    }
    /******************************************/
    int i1;
};
/******************************************/

typedef boost::shared_ptr< Derived1 > Derived1Ptr;
/******************************************/

class Derived2 : public Base
{
public:
    void derived2_test()
    {
        cout << "derived2_test" << endl;
    }
    /******************************************/
    int i2;
};
/******************************************/

typedef boost::shared_ptr< Derived2 > Derived2Ptr;
/******************************************/

int main()
{
    Derived1Ptr d1 = boost::make_shared< Derived1 >();
    Derived2Ptr d2 = boost::make_shared< Derived2 >();

    vector< BasePtr > v;
    v.push_back( d1 );
    v.push_back( d2 );
    BOOST_FOREACH(BasePtr bPtr,v)
    {
        try
        {
            Derived1& d11 = dynamic_cast< Derived1& >( *bPtr );
            d11.derived1_test();
        }
        catch (const std::bad_cast& e)
        {
            Derived2& d22 = dynamic_cast< Derived2& >( *bPtr );
            d22.derived2_test();
        }
    }
    return 0;
}

在上面的代码中,如果我更改BOOST_FOREACH中的代码

Derived1& d11 = dynamic_cast< Derived1& >( *bPtr );

Derived1Ptr d11 = dynamic_cast< Derived1Ptr >( bPtr );

,我在VS2010上得到以下编译时错误

invalid target type for dynamic_cast target type must be a pointer or reference to a defined class

我的问题是我想使用boost :: shared_ptr不参考.其次,当对象引用是不同的类型(尝试使用共享指针,但是获得前面提到的编译器错误)时,我正在使用dynamic_cast将抛出一个std :: bad_cast异常.这显然很慢我想要能够使用更加面向性能的方法.我正在寻找的是任何解决方案,而不是使用dynamic_cast和异常处理.

欢迎任何关于代码或设计变更的建议.

解决方法

使用 dynamic_pointer_cast

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读