创建常量share_ptr<pure_virtual_class>成员

Creating a const share_ptr<pure_virtual_class> member

本文关键字:virtual class gt pure 成员 lt 常量 share ptr 创建      更新时间:2023-10-16

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

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;
};

我怎样才能得到这个功能?

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

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;
};

在像下面这样的简单情况下:

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 ) )
    {
    }
};

这将允许任何可以想象的逻辑(以及更复杂的逻辑集合)