Reputation: 10539
May I have a "dangling reference" with the following code (in an eventual slot connected to the myQtSignal)?
class Test : public QObject
{
Q_OBJECT
signals:
void myQtSignal(const FooObject& obj);
public:
void sendSignal(const FooObject& fooStackObject)
{
emit myQtSignal(fooStackObject);
}
};
void f()
{
FooObject fooStackObject;
Test t;
t.sendSignal(fooStackObject);
}
int main()
{
f();
std::cin.ignore();
return 0;
}
Particularly if emit and slot are not executed in the same thread.
Upvotes: 30
Views: 28712
Reputation: 8311
I'm sorry to continue a subject years old but it came up on Google. I want to clarify HostileFork's answer as it may mislead future readers.
Passing a reference to a Qt signal is not dangerous thanks to the way signal/slot connections work:
emit MySignal(my_string)
returns all directly connected slots have been executed.https://doc.qt.io/qt-5/qt.html#ConnectionType-enum
Upvotes: 33
Reputation: 4424
No, you won't encounter a dangling reference. At least, not unless your slot does the sort of things that would cause problems in regular functions too.
Qt::DirectionConnection
We can generally accept that this won't be a problem for direct connections as those slots are called immediately. Your signal emission blocks until all slots have been called. Once that happens, emit myQtSignal(fooStackObject);
will return just like a regular function. In fact, myQtSignal(fooStackObject);
is a regular function! The emit keyword is entirely for your benefit--it does nothing. The signal function is just special because its code is generated by Qt's compiler: the moc.
Qt::QueuedConnection
Benjamin T has pointed out in the documentation that arguments are copied, but I think it's enlightening to explore how this works under the hood (at least in Qt 4).
If we start by compiling our project and searching around for our generated moc file, we can find something like this:
// SIGNAL 0
void Test::myQtSignal(const FooObject & _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
So basically, we pass a number of things to QMetaObject::activate
: our QObject, the metaObject for our QObject's type, our signal id, and a pointer to each of the arguments our signal received.
If we investigate QMetaObject::activate
, we'll find it's declared in qobject.cpp. This is something integral to how QObjects work. After browsing through some stuff that's irrelevant to this question, we find the behaviour for queued connections. This time we call QMetaObject::queued_activate
with our QObject, the signal's index, an object representing the connection from signal to slot, and the arguments again.
if ((c->connectionType == Qt::AutoConnection && !receiverInSameThread)
|| (c->connectionType == Qt::QueuedConnection)) {
queued_activate(sender, signal_absolute_index, c, argv ? argv : empty_argv);
continue;
Having reached queued_activate, we've finally arrived at the real meat of the question.
First, it builds a list of connection types from the signal:
QMetaMethod m = sender->metaObject()->method(signal);
int *tmp = queuedConnectionTypes(m.parameterTypes());
The important thing in queuedConnectionTypes is that it uses QMetaType::type(const char* typeName)
to get the metatype id of the argument type from the signal's signature. This means two things:
The type must have a QMetaType id, thus it must have been registered with qRegisterMetaType
.
Types are normalized. This means "const T&" and "T" map to the QMetaType id for T.
Finally, queued_activate passes the signal argument types and the given signal arguments into QMetaType::construct
to copy-construct new objects with lifetimes that will last until the slot has been called in another thread. Once the event has been queued, the signal returns.
And that's basically the story.
Upvotes: 21
Reputation: 33617
UPDATE 20-APR-2015
Originally I believed that passing a reference to a stack-allocated object would be equivalent to passing the address of that object. Hence in the absence of a wrapper that would store a copy (or a shared pointer), a queued slot connection could wind up using the bad data.
But it was raised to my attention by @BenjaminT and @cgmb that Qt actually does have special handling for const reference parameters. It will call the copy constructor and stow away the copied object to use for the slot calls. Even if the original object you passed has been destroyed by the time the slot runs, the references that the slots get will be to different objects entirely.
You can read @cgmb's answer for the mechanical details. But here's a quick test:
#include <iostream>
#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
class Param {
public:
Param () {}
Param (Param const &) {
std::cout << "Calling Copy Constructor\n";
}
};
class Test : public QObject {
Q_OBJECT
public:
Test () {
for (int index = 0; index < 3; index++)
connect(this, &Test::transmit, this, &Test::receive,
Qt::QueuedConnection);
}
void run() {
Param p;
std::cout << "transmitting with " << &p << " as parameter\n";
emit transmit(p);
QTimer::singleShot(200, qApp, &QCoreApplication::quit);
}
signals:
void transmit(Param const & p);
public slots:
void receive(Param const & p) {
std::cout << "receive called with " << &p << " as parameter\n";
}
};
...and a main:
#include <QCoreApplication>
#include <QTimer>
#include "param.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// name "Param" must match type name for references to work (?)
qRegisterMetaType<Param>("Param");
Test t;
QTimer::singleShot(200, qApp, QCoreApplication::quit);
return a.exec();
}
Running this demonstrates that for each of the 3 slot connections, a separate copy of the Param is made via the copy constructor:
Calling Copy Constructor
Calling Copy Constructor
Calling Copy Constructor
receive called with 0x1bbf7c0 as parameter
receive called with 0x1bbf8a0 as parameter
receive called with 0x1bbfa00 as parameter
You might wonder what good it does to "pass by reference" if Qt is just going to make copies anyway. However, it doesn't always make the copy...it depends on the connection type. If you change to Qt::DirectConnection
, it doesn't make any copies:
transmitting with 0x7ffebf241147 as parameter
receive called with 0x7ffebf241147 as parameter
receive called with 0x7ffebf241147 as parameter
receive called with 0x7ffebf241147 as parameter
And if you switched to passing by value, you'd actually get a more intermediate copies, especially in the Qt::QueuedConnection
case:
Calling Copy Constructor
Calling Copy Constructor
Calling Copy Constructor
Calling Copy Constructor
Calling Copy Constructor
receive called with 0x7fff15146ecf as parameter
Calling Copy Constructor
receive called with 0x7fff15146ecf as parameter
Calling Copy Constructor
receive called with 0x7fff15146ecf as parameter
But passing by pointer doesn't do any special magic. So it has the problems mentioned in the original answer, which I'll keep below. But it has turned out that reference handling is just a different beast.
ORIGINAL ANSWER
Yes, this can be dangerous if your program is multithreaded. And it's generally poor style even if not. Really you should be passing objects by value over signal and slot connections.
Note that Qt has support for "implicitly shared types", so passing things like a QImage "by value" won't make a copy unless someone writes to the value they receive:
http://qt-project.org/doc/qt-5/implicit-sharing.html
The problem isn't fundamentally anything to do with signals and slots. C++ has all kinds of ways that objects might be deleted while they're referenced somewhere, or even if some of their code is running in the call stack. You can get into this trouble easily in any code where you don't have control over the code and use proper synchronization. Techniques like using QSharedPointer can help.
There are a couple of additional helpful things Qt offers to more gracefully handle deletion scenarios. If there's an object you want to destroy but you are aware that it might be in use at the moment, you can use the QObject::deleteLater() method:
http://qt-project.org/doc/qt-5/qobject.html#deleteLater
That's come in handy for me a couple of times. Another useful thing is the QObject::destroyed() signal:
Upvotes: 37
Reputation: 75150
If the scope in which an object exists ends and it is then used, it will refer to a destroyed object which will cause undefined behaviour. If you are not sure whether the scope will end, it is best to allocate the object on the free store via new
and use something like shared_ptr
to manage its lifetime.
Upvotes: 0