【问题标题】:Creating a const share_ptr<pure_virtual_class> member创建一个 const shared_ptr<pure virtual class> 成员
【发布时间】:2011-12-21 06:52:48
【问题描述】:

我有许多从纯虚基派生的类:

class base {
public:
    virtual int f() = 0;
};

class derived_0 : public base {
public:
    int f() {return 0;}
};

class derived_1 : public base {
public:
    int f() {return 1;}
};

为了简洁起见,我只放了两个派生类,但实际上我还有更多。

我想创建一个类,它有一个指向基的 const 共享指针。我想执行以下操作,但我不能,因为我必须在初始化列表中初始化 const 指针:

class C{
public:
    C(bool type) { 
        if(type) {
            derived_0* xx = new derived_0;
            x = shared_ptr<base>( xx );
        }
        else {
            derived_1* xx = new derived1;
            x = shared_ptr<base>( xx );
        }
    } 
private:
    const share_ptr<base> x;
};

如何获得此功能?

【问题讨论】:

  • 您忘记将base::f() 标记为virtual
  • 我想知道错误信息到底是什么。

标签: c++ boost initialization shared-ptr member


【解决方案1】:

您将对象的创建封装在一个函数中,如下所示:

shared_ptr<base> create_base(bool type) {
     if(type) {
         return make_shared<derived_0>();
     }
     else {
         return make_shared<derived_1>();
     }
}

然后你可以在你的初始化列表中使用它:

class C{
public:
    C(bool type)
    : x(create_base(type))
    {}
private:
    const share_ptr<base> x;
};

【讨论】:

    【解决方案2】:

    在像这个精确示例这样的简单情况下:

    class C
    {
        shared_ptr<Base> const x;
    public:
        C( bool type ) 
            : x( type
                ? static_cast<Base*>( new Derived_0 )
                : static_cast<Base*>( new Derived_1 ) )
        {
        }
    };
    

    (是的,static_cast 或至少其中一个是必需的。)

    在更一般的情况下,决策逻辑更复杂,您可以 可能想要创建一个返回 shared_ptr 的静态函数, 例如:

    class C
    {
        shared_ptr<Base> const x;
        static shared_ptr<Base> makeSharedPtr( bool type );
    public:
        C( bool type )
            : x( makeSharedPtr( type ) )
        {
        }
    };
    

    这将允许任何可以想象的逻辑(以及更复杂的一组 参数)。

    【讨论】:

    • 请注意,在您使用三元运算符的第一种情况下,像这样使用 static_cast 意味着析构函数必须是虚拟的。如果您改为创建一个临时的shared_ptr,则指针本身可以保存确切的派生类以供以后删除。
    • @MarkB 但是一般来说,如果一个类是多态的,你希望析构函数是虚拟的。
    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 2018-11-18
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2014-12-16
    相关资源
    最近更新 更多