gpt4 book ai didi

c++ - QEvent所有权

转载 作者:行者123 更新时间:2023-11-30 01:47:58 25 4
gpt4 key购买 nike

我想将预定义和自定义的 QEvent 发送到 Qt 应用程序。需要的事件是在堆上分配还是我可以将指针传递给堆栈上的对象?

QKeyEvent stackevent(QEvent::KeyPress);
QKeyEvent* heapevent = new QKeyEvent(QEvent::KeyPress);

QEvent * event;
event = &stackevent; //valid ??
event = heapevent;
QCoreApplication()->notify(someobj, event);
delete heapevent; //valid? or lost ownership?

最佳答案

event = &stackevent; //valid ??

通常这是不安全的,但在这种情况下是有效的,因为函数 notify不会返回,直到有人处理(或不处理)事件(这意味着 stackevent 在此操作期间将“活着”)。

delete heapevent; //valid? or lost ownership?

是的,这也是有效的,因为通常没有人应该持有指向 QEvent 的指针(当然也删除它),顺便说一句,它已经被处理过了。

postEvent 时,情况显着 发生了变化。使用:

The event must be allocated on the heap since the post event queue will take ownership of the event and delete it once it has been posted. It is not safe to access the event after it has been posted.

好吧,我想在您的情况下使用堆栈分配并在出现任何可能的问题时传递指向它的指针(内存将自动释放)更合适。

关于c++ - QEvent所有权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30895304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com