UmNyobe
UmNyobe

Reputation: 22890

QEvent ownership

I want to send both predefined and custom QEvent to a Qt application. Is the event required be allocated on the heap or can I just pass the pointer to a object on the stack?

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?

Upvotes: 2

Views: 861

Answers (1)

dazewell
dazewell

Reputation: 436

event = &stackevent; //valid ??

Usually that's not safe, but in this case it's valid, because the function notify won't return, untill the event is handled (or not) by someone (it means that stackevent will be "alive" during this operation).

delete heapevent; //valid? or lost ownership?

Yap, that's valid too, because normally nobody should hold a pointer to the QEvent (and delete it, of course) and btw it has already been processed.

The situation significantly changes when postEvent is used:

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.

Well, I guess it's more suitable to use stack allocation in your situation and passing a pointer to it in case of any possible problems (memory automatically will be released).

Upvotes: 4

Related Questions