סטנלי גרונן
סטנלי גרונן

Reputation: 3007

Qt: How to properly define the signal argument for this code?

I am using Qt 4.8 on Ubuntu 14.04.
Currently, I have the following piece of code:

void MyServer::processMessage()
{
   QByteArray data;
   ...

   ...
   emit newMessage(data);
}   

--
What would be the proper way to define the newMessage signal (in the header file):

signals:
    void newMessage(const QByteArray & newData);

or:

signals:
    void newMessage(QByteArray newData);

As seen above, the signal is emitted right before exiting the processMessage function, so the QByteArray data won't exist anymore immediately after emitting that signal...
So, my worries about the first way of defining the signal is that it passes as an argument a reference to an object (instance) that doesn't exist anymore after newMessage is emitted.

Thanks in advance for your time and patience!
BTW: My app is single-thread.
PS: Would things differ if app would be multi-threaded?

Upvotes: 2

Views: 2457

Answers (2)

Kevin Krammer
Kevin Krammer

Reputation: 5207

Both are ok, though the most common version would be

signals:
    void newMessage(const QByteArray &newData);

Regarding your worries about your first option: passing a reference can only be done with Qt::DirectConnection (which Qt::AutoConnection bascially results in for a single threaded signal/slot connection), as the others require that signal arguments are storable in QVariant and references aren't.

With such a Qt::DirectConnection the emit will "return" when all slots connected to the signal have been executed. So at this point nobody will need the data object anymore.

Upvotes: 2

J. Piquard
J. Piquard

Reputation: 1663

As described in the previous answer 'how to pass qobject as argument from signal to slot in qt connect', it is recommanded to pass Object as pointer.

So, the signals declaration is:

signals:
    void newMessage(QByteArray* newData);

And the emission of signal is:

void MyServer::processMessage()
{
   QByteArray data;
   ...

   ...
   emit newMessage(&data);
} 

Upvotes: 1

Related Questions