【发布时间】:2017-08-12 12:03:06
【问题描述】:
为什么这不起作用?
类继承自 QObject
b 是子类。
bar 是 Foo 孩子。
void Class::method(Foo& b) {
Bar* bar = b.getBar();
QObject::connect(bar, &Bar::s1, [&]{
auto x = bar->x(); // this line throw an exception read access violation.
});
}
作为第一个猜测,我认为调用插槽时该栏不再存在。要纠正它,我需要按值捕获。
我说对了吗?
使其工作的更改:
void Class::method(Foo& b) {
Bar* bar = b.getBar();
QObject::connect(bar, &Bar::s1, [bar]{
auto x = bar->x(); // this line throw no more exceptions and work as expected.
});
}
【问题讨论】:
-
什么是
Foo::getBar? -
它创建一个 Bar* 并将其父级设置为 Foo。
-
可能是因为
bar在调用信号时不再有效。 -
请注意,您可以将“保护对象”作为第三个参数传递给
connect(您的 lambda 然后是第四个),如果保护对象被破坏,它将破坏与 lambda 的连接。在这种情况下,您可能希望使用bar作为守卫(需要Qt 5.2 或更高版本)。所以QObject::connect(bar, &Bar::s1, bar, [&]{.... -
bar 是 b child 而 b 是 Class child 我确定它存在。
标签: c++ qt lambda qt-signals qt-slot