C++:引用和工厂

jma*_*jma 3 c++ c++11

我有这样的事情:

struct D {
    virtual void operator() {...};
}
struct D1 : public D {
    virtual void operator() {...};
}
struct D2 : public D {
    virtual void operator() {...};
}

void foo(D &d) {...};
Run Code Online (Sandbox Code Playgroud)

所以这很好,很好地控制了我的D的生命周期:

foo(D());
foo(D1());
foo(D2());
Run Code Online (Sandbox Code Playgroud)

但我在多个地方选择我的D变种,所以我想要一个简单的工厂:

const D& make_D()
{
    // BAD, returning reference to temporary
    if(is_tuesday())
        return D1();
    return D2();
}
Run Code Online (Sandbox Code Playgroud)

我可以返回一个对象,而不是返回对临时的引用,然后切换到基类.或者,我可以从我的工厂返回一个指针,但客户端必须删除它.其他更复杂的解决方案也会给客户带来更多负担.

有没有办法写出类似的东西

D& d = make_D();
foo(d);
Run Code Online (Sandbox Code Playgroud)

(甚至foo(make_D()))?目标是将复杂性包含在各种D定义中,make_D()以便函数foo()和调用这些函数的函数不必担心它.

Luc*_*ore 5

通常的方法是返回指针或智能指针.

使用指针的缺点是让用户管理其内存.

如果返回智能指针,则不再是问题.

const SmartPtr<D> make_D()
{
    if(is_tuesday())
        return SmartPtr(new D1());
    return SmartPtr(new D2());
}
Run Code Online (Sandbox Code Playgroud)


BЈо*_*вић 5

不幸的是,这是不可能的.

通常,我所做的就是使用std::unique_ptr(有时std::shared_ptr,当不可能使用时std::unique_ptr):

typedef std::unique_ptr< D > Dptr;
Dptr make_D()
{
    Dptr p( nulptr );

    if(is_tuesday())
        p.reset( new D1 );
    else
        p.reset( new D2 );

    return p;
}
Run Code Online (Sandbox Code Playgroud)