管理事件的传播:指针还是实例?
我正在编写一个事件处理系统(遵循观察者模式...),我想知道哪种是传播或传播事件类的最佳方式,如下所示:
class Event{
public:
Event(int code);
virtual ~Event();
int getCode() const;
private:
int code;
};
详细说明是否最好发送它通过指针(堆分配)或作为实例(堆栈分配)。
Event e(1);
notifyAll(e);
vs
Event * e = new Event(1);
notifyAll(e)
我知道这是一个非常常见的问题,并且我知道针对一般情况的建议指南,但我想知道在特定情况下事件处理负责性能、优化、线程安全等。
我的想法是通过堆栈分配发送,看到该类只是一个 POD,并避免生命管理问题(或使用智能指针)。 另一方面,我的应用程序中的事件传播树可能非常大,所以我担心这可能是一个问题。
谢谢。 (例如,如果您知道任何好的实现,不像qt那么复杂,可以学习,请写下来)
I'm coding an event handling system ( following observer pattern... ) and I'd like to know which is the best way to propagate or spread an Event class, something like this:
class Event{
public:
Event(int code);
virtual ~Event();
int getCode() const;
private:
int code;
};
In detail if better to send it through a pointer (heap allocated) or as an instance (stack allocated).
Event e(1);
notifyAll(e);
vs
Event * e = new Event(1);
notifyAll(e)
I know it's a really common question, and i know the suggested guidelines for generic cases,but i would like to know in the specific case of event handling taking care of performance, optimization, being thread safe and so on.
My idea is to send through stack allocation, seen that the class is just a POD, and to avoid life managing issues ( or using smart pointers ).
On the other side the event propagation tree could be really big in my apps, so I'm afraid it could be an issue.
Thank you.
(For instance if you are aware of any good implementation, not as complicated as in qt, to learn from please write it down)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果通过引用传递堆栈分配的对象,则与通过指针传递之间没有性能差异。
如果您通过指针传递,则某些代码必须负责
删除
对象。 OTOH,如果对象的生命周期需要持续超出其创建的范围,那么您将被迫进行动态分配。在这种情况下,也许您可能需要进行引用计数。如果没有更多信息,很难说。If you pass a stack-allocated object by reference, there is no performance difference between that and passing by pointer.
If you pass by pointer, then some piece of code has to be responsible for
delete
-ing the object. OTOH, if the lifetime of the object needs to persist beyond the scope in which it's created, then you're forced to do dynamic allocation. In that case, perhaps you might need to do reference-counting. It's hard to say without more information.