创建const share_ptr <pure_virtual_class>成员

Mar*_*sar 2 c++ boost initialization member shared-ptr

我有许多类来自纯粹的基础:

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;}
};
Run Code Online (Sandbox Code Playgroud)

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

我想创建一个具有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;
};
Run Code Online (Sandbox Code Playgroud)

我该如何获得此功能?

Bjö*_*lex 6

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

shared_ptr<base> create_base(bool type) {
     if(type) {
         return make_shared<derived_0>();
     }
     else {
         return make_shared<derived_1>();
     }
}
Run Code Online (Sandbox Code Playgroud)

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

class C{
public:
    C(bool type)
    : x(create_base(type))
    {}
private:
    const share_ptr<base> x;
};
Run Code Online (Sandbox Code Playgroud)