简体   繁体   English

创建一个const share_ptr <pure_virtual_class> 会员

[英]Creating a const share_ptr<pure_virtual_class> member

I have a number of classes that derive from a pure virtal base: 我有许多类来自纯粹的基础:

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

I only put two derived classes for brevity, but in practice I have more. 为了简洁,我只放了两个派生类,但实际上我有更多。

And I would like to create a class that has a const shared pointer to the base. 我想创建一个具有const共享指针的类。 I would like do to the following but I can't as I must initialize the const pointer in the initialization list: 我想做以下但我不能,因为我必须初始化初始化列表中的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;
};

How can I get this functionality? 我该如何获得此功能?

You encapsulate the creation of the object in a function, like this: 您将对象的创建封装在函数中,如下所示:

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

And then you can use it in your initialization-list: 然后你可以在初始化列表中使用它:

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

In simple cases like this precise example: 在这种简单的例子中,这个精确的例

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

(And yes, the static_cast , or at least one of them, are necessary.) (是的, static_cast ,或至少其中一个,是必要的。)

In more general cases, where the decision logic is more complex, you might want to create a static function which returns the shared_ptr , eg: 在更一般的情况下,决策逻辑更复杂,您可能想要创建一个返回shared_ptr的静态函数,例如:

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

This will allow any imaginable logic (and a more complex set of parameters as well). 这将允许任何可以想象的逻辑(以及更复杂的参数集)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM