C ++:引用和工厂(C++: references and factories)

编程入门 行业动态 更新时间:2024-10-11 23:27:35
C ++:引用和工厂(C++: references and factories)

我有这样的事情:

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

更多推荐

本文发布于:2023-07-15 07:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1111441.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:工厂   references   factories

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!