堆栈对象Qt信号和参数作为参考
我可以有一个带有以下代码的“悬空引用”(在连接到 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;
}
特别是如果emit 和slot 不在同一个线程中执行。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更新 20-4-2015
最初 我认为传递对堆栈分配对象的引用相当于传递该对象的地址。因此,在没有存储副本(或共享指针)的包装器的情况下,排队的槽连接可能会使用错误数据。
但 @BenjaminT 和 @cgmb 引起了我的注意,Qt 实际上确实对 const 引用参数有特殊处理。它将调用复制构造函数并存放复制的对象以用于槽调用。即使您传递的原始对象在插槽运行时已被销毁,插槽获得的引用也将完全是不同的对象。
您可以阅读 @cgmb 的回答了解机械详细信息。但这里有一个快速测试:
...和一个主要的:
运行这个演示了对于 3 个槽连接中的每一个,通过复制构造函数创建了一个单独的 Param 副本:
您可能想知道“通过引用传递”有什么好处“如果 Qt 无论如何都要复制的话。但是,它并不总是进行复制......这取决于连接类型。如果您更改为
Qt::DirectConnection
,它不会制作任何副本:如果您切换为按值传递,您实际上会获得更多的中间副本,特别是在 Qt::QueuedConnection 情况下:
但是通过指针传递并不会产生任何特殊的魔力。所以它存在原始答案中提到的问题,我将在下面保留。但事实证明,引用处理只是一个不同的野兽。
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:
...and a main:
Running this demonstrates that for each of the 3 slot connections, a separate copy of the Param is made via the copy constructor:
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:And if you switched to passing by value, you'd actually get a more intermediate copies, especially in the
Qt::QueuedConnection
case: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.
我很抱歉要继续讨论一个多年前的话题,但它出现在谷歌上。我想澄清 HostileFork 的答案,因为它可能会误导未来的读者。
由于信号/槽连接的工作方式,传递对 Qt 信号的引用并不危险:
emit MySignal(my_string)
直接返回全部时连接的槽已被执行。https://doc.qt.io/qt-5/qt.html #ConnectionType-enum
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
不,您不会遇到悬空引用。至少,除非你的插槽执行的操作也会导致常规函数出现问题。
Qt::DirectionConnection
我们通常可以接受,这对于直接连接来说不会成为问题,因为这些插槽会立即被调用。您的信号发射会阻塞,直到所有插槽都被调用。一旦发生这种情况,
emit myQtSignal(fooStackObject);
将像常规函数一样返回。事实上,myQtSignal(fooStackObject);
是一个常规函数! emit 关键字完全是为了你的利益——它什么也不做。信号函数很特殊,因为它的代码是由 Qt 的编译器生成的:moc。Qt::QueuedConnection
Benjamin T 在文档中指出了参数被复制,但我认为探索它在幕后如何工作(至少在 Qt 4 中)是有启发性的。
如果我们首先编译我们的项目并搜索生成的 moc 文件,我们可以找到类似这样的内容:
所以基本上,我们将许多东西传递给 QMetaObject::activate:我们的 QObject,元对象对于我们的 QObject 类型、我们的信号 ID 以及指向我们信号接收到的每个参数的指针。
如果我们调查
QMetaObject::activate
,我们会发现它在qobject.cpp中声明。这是 QObject 工作方式中不可或缺的一部分。在浏览了一些与这个问题无关的内容后,我们发现了排队连接的行为。这次我们调用QMetaObject::queued_activate
与我们的 QObject、信号的索引、表示从信号到槽的连接的对象以及参数。到达queued_activate 后,我们终于到达了问题的实质。
首先,它根据信号构建一个连接类型列表:
queuedConnectionTypes 中重要的是它使用 QMetaType::type(const char* typeName) 来从信号的签名。这意味着两件事:
该类型必须有一个 QMetaType id,因此它必须已使用
qRegisterMetaType
。类型是标准化的。这意味着“const T&”和“T”映射到 T 的 QMetaType id。
最后,queued_activate 将信号参数类型和给定的信号参数传递到
QMetaType::construct
复制构造新对象,其生命周期将持续到在另一个线程中调用该槽为止。一旦事件排队,信号就会返回。故事基本上就是这样。
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:
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 callQMetaObject::queued_activate
with our QObject, the signal's index, an object representing the connection from signal to slot, and the arguments again.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:
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.
如果对象存在的范围结束并且随后使用它,它将引用一个被销毁的对象,这将导致未定义的行为。如果您不确定作用域是否会结束,最好通过
new
在自由存储上分配对象,并使用shared_ptr
之类的东西来管理其生命周期。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 likeshared_ptr
to manage its lifetime.