管理事件的传播:指针还是实例?

发布于 2024-11-02 07:49:32 字数 602 浏览 0 评论 0原文

我正在编写一个事件处理系统(遵循观察者模式...),我想知道哪种是传播或传播事件类的最佳方式,如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

安静 2024-11-09 07:49:32

如果通过引用传递堆栈分配的对象,则与通过指针传递之间没有性能差异。

如果您通过指针传递,则某些代码必须负责删除对象。 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文