Passing references in signals and slots
-
Hello,
I'm sorry if the answer is available somewhere in the documentation, I'm just not sure where to look.
If I pass a custom object (it may not be necessarily a QObject) by reference in signals and slots, will it be truly passed by reference, or will it get copied anyway?
Is the answer to the above question likely to change in the future versions of Qt?
Thank you.
-
You can only pass const references. And they will not be copied except the connection is a queued connection or the slot does not take const references but values.
-
Hello,
I'm sorry if the answer is available somewhere in the documentation, I'm just not sure where to look.
If I pass a custom object (it may not be necessarily a QObject) by reference in signals and slots, will it be truly passed by reference, or will it get copied anyway?
Is the answer to the above question likely to change in the future versions of Qt?
Thank you.
@Pippin
As @Christian-Ehrlicher has written. But be aware that if your object isQObject
-derived it cannot be copied anyway, so at least in a queued connection/cross-thread you presumably cannot do something which would require copying.Normally objects, including
QObject
s, are/should be passed as a pointer. I think (just about) every Qt function which accepts aQObject
does so as aQObject *
not aQObject &
. Of course you have to be careful about accessing it certainly if cross-thread, e.g. mutexs and UI objects, likeQWidget
s, must not be accessed from a secondary thread. -
-
If the object itself isn't const, but I pass it as a const reference through signals and slots, I guess that still works? As long as the signals and slots are declared with
const&
@Pippin said in Passing references in signals and slots:
If the object itself isn't const, but I pass it as a const reference through signals and slots, I guess that still works? As long as the signals and slots are declared with const&
Yes, it is sufficient if it is declared
const&
in the signals and slots.