[Qt-interest] Safety of Passing by Reference with Signals andSlots
Will Rutherdale (rutherw)
rutherw at cisco.com
Fri May 1 21:09:58 CEST 2009
Thanks, that sounds reassuring. It sounds like you're saying it will
copy my parameter data into the queue on an emit, so I can pass by
reference and be safe. It sounds like you're saying it allocates a
QEvent object and frees it, or something equivalent.
Regarding your criteria, my struct would have default copy constructors,
but had no Q_DECLARE_METATYPE or qRegisterMetaType. I am familiar with
these names, as I have used them in other parts of the code involving
QtDBus. However, for the simple emit statements that are used within
one process to talk to different threads, I have not used them.
When I actually tested the code, it worked. All the data got through.
There were no warnings or error messages at any stage. What is supposed
to go wrong if I don't provide Q_DECLARE_METATYPE or qRegisterMetaType?
Thanks for responding.
-Will
-----Original Message-----
From: qt-interest-bounces at trolltech.com
[mailto:qt-interest-bounces at trolltech.com] On Behalf Of Thiago Macieira
Sent: 1 May 2009 14:47
To: qt-interest at trolltech.com
Subject: Re: [Qt-interest] Safety of Passing by Reference with Signals
andSlots
Will Rutherdale (rutherw) wrote:
>For this purpose I use connect() with Qt::QueuedConnection and emit.
>Right now the signal and slot prototypes look something like this:
>
>
>
>signals: // in computation class
>
> void sigSendResult( ResultStruct const &ppr );
>
>
>
>private slots: // in control class
>
> void reportResult( ResultStruct const &ppr );
>
>
>
>My question is this: how safe is it to pass by reference in this
>situation?
Very safe.
All arguments in a QueuedConnection are copied onto the event that
transports the signal from one thread into another. So your emitting
code
can safely have the objects for which the references were created
destroyed. They can even be temporaries.
The queued emission system also takes care of properly deleting the
copies
when the event has been delivered.
Also note that the signal-slot system treats pass-by-constant-reference
to
be the same as pass-by-value.
That also has two important implications:
1) you can only emit signals via queued connections if all argument
types
are copiable, declared with Q_DECLARE_METATYPE and registered with
qRegisterMetaType. The registering has to happen before the signal is
emitted.
2) passing by pointer is possible, but all it accomplishes is copying
of
the pointer value, not of the object being pointed to
--
Thiago Macieira - thiago.macieira (AT) nokia.com
Senior Product Manager - Nokia, Qt Software
Sandakerveien 116, NO-0402 Oslo, Norway
More information about the Qt-interest-old
mailing list