我有这样的事情:
struct D { virtual void operator() {...}; } struct D1 : public D { virtual void operator() {...}; } struct D2 : public D { virtual void operator() {...}; } void foo(D &d) {...};所以这很好,很好地控制了我的D的生命周期:
foo(D()); foo(D1()); foo(D2());但我在多个地方选择我的D变体,所以我想要一个简单的工厂:
const D& make_D() { // BAD, returning reference to temporary if(is_tuesday()) return D1(); return D2(); }我可以返回一个对象,而不是返回一个临时对象的引用,然后切片到基类。 或者,我可以从我的工厂返回一个指针,但客户端必须删除它。 其他更复杂的解决方案也会给客户带来更多负担。
有没有办法写出类似的东西
D& d = make_D(); foo(d);(甚至foo(make_D()) )? 目标是将复杂性包含在各种D定义中和make_D()以便像foo()和那些调用这些函数的函数不需要担心它。
I have something like this:
struct D { virtual void operator() {...}; } struct D1 : public D { virtual void operator() {...}; } struct D2 : public D { virtual void operator() {...}; } void foo(D &d) {...};And so this is fine, and nicely controls the life cycle of my D's:
foo(D()); foo(D1()); foo(D2());But I choose my D variant in multiple places, so I want a simple factory:
const D& make_D() { // BAD, returning reference to temporary if(is_tuesday()) return D1(); return D2(); }Instead of returning a reference to a temporary, I could return an object, but then I slice to the base class. Alternatively, I could return a pointer from my factory, but then the client has to delete it. Other, more complicated, solutions also impose more load on the client.
Is there a way to write something like
D& d = make_D(); foo(d);(or even foo(make_D()))? The goal is to wrap the complexity in the various D definitions and in make_D() so that the functions like foo() and those who call those functions needn't worry about it.
最满意答案
通常的方法是返回一个指针或一个智能指针。
使用指针的缺点是让用户管理其内存。
如果你返回一个智能指针,这不再是一个问题。
const SmartPtr<D> make_D() { if(is_tuesday()) return SmartPtr(new D1()); return SmartPtr(new D2()); }The usual way is to either return a pointer or a smart pointer.
The downside of using a pointer is letting the user manage its memory.
If you return a smart pointer, this is no longer an issue.
const SmartPtr<D> make_D() { if(is_tuesday()) return SmartPtr(new D1()); return SmartPtr(new D2()); }更多推荐
发布评论