how to handle emit signal(dynamically allocated item that needs to be freed)
-
Hello,
I have a dynamically allocated object which is a parameter passed to a signal with an emit signal(object); type code.
How/when can I safely delete my object.pseudo code:
Type *a= new Type(paramters);
some_Processing_On_a();
emit aHasChanged(a);Thanks,
Cyrille -
@Cyrille-de-Brebisson Are you passing by reference, or as pointer?
You can let the receiving slot delete it, but if you connect more than one slot then you will be in trouble.
You should consider using smart pointers for that instead of raw pointers - smart pointer will delete the object as soon as nobody references it anymore. -
Hello,
At the moment, I am passing my data (variable size) by address (the data is raw allocated (malloc) ram)... but I could change things if needed.
They seem to be a VERY large number of smart pointer types in QT, any indication on which one I should use?
Since the slot/signal system seems to do a lot of (void*) cast, I am afraid that smart pointers might not work well as they might miss a copy somewhere...
Cyrille
-
if you are 100% sure no slot will ever be executed in a secondary thread (or executed by forcing
Qt::QueuedConnection
) then you can safely calldelete a;
just afteremit aHasChanged(a);
hey seem to be a VERY large number of smart pointer types in QT, any indication on which one I should use?
https://doc.qt.io/qt-5/qsharedpointer.html
I am afraid that smart pointers might not work well as they might miss a copy somewhere
As long as they are declared with the meta-object system you don't have to worry about anything.
QSharedPointer
is automatically registered so no worries -
hello,
ok, I will try it, thanks.
cyrille