简体   繁体   中英

Qt signal/slots and C++ Lambda expression

Why this doesn't work ?

Class inherit from QObject

b is Class child.

bar is Foo child.

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.
    });
}

As first guess I think the bar is no longer exist when the slot is called. to correct it I need to capture by value.

Am I getting it right ?.

CHANGES THAT MAKE IT WORK:

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.
    });
}

bar is local pointer variable. When you capture by reference it's the same as to capture [&bar] , which type it Bar** . After that you try to access to bar in lambda assuming that pointer to Bar is located by captured &bar address. And it is not true because local variable was destroyed. The actual object of type Bar is remains located by the same address, but this address is corrupted when capturing by [&] . So it's correct to change capture to [bar] and thus capturing pointer directly, not the address where this pointer can be found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM