Qt5 slot lambda why captured local variable is random for the first time lambda is called

Advertisements

In the following code, I think p2 should print 10. But in fact it prints random value. The I starts to understand why it is not 10, with the following (1)-(3) thougths.

{
    int m = 10; // local var m
    qDebug() << "m0: " << &m;
    connect(btn2, &QPushButton::clicked, this, [&]() { qDebug() << "m2: " << &m; qDebug() << "p2 " << m; m = 20; qDebug() << "p22 " << m; }); // captured var m
} 

output:

m0:  0x8ff8ac
p0  10
m2:  0x8ff8ac
p2  11974204
p22  20
m2:  0x8ff8ac
p2  20
p22  20

(1). The first time lambda is called, its captured var m has random value. I think this may because local var m is a local variable, and it is on stack memory, which is released after }, and it is random thereafter.

(2). After captured m is assigned 20 inside lambda, when it is called a second time, m remains 20. Which is against what I think in (1), because when quits lambda function, m memory should be released, and thereafter random value again.

(3).[&] enables lambda to access memory that is released, isn’t it dangerous?

Based on my above thoughts, my question would be why captured m is not 10 (what p2 prints)? why a released memory could be accessed and modified, isn’t it dangerous? why a second visit of lambda, m is not random?

>Solution :

Because you capture it by reference.

Once the function ends, so does the life-time of all its local variables. The local variables cease to exist. Any reference or pointer to them will become invalid. Using such references or dereferencing such pointers will lead to undefined behavior.

The life-time of all variables captured by reference must be at least as long as the life-time of the lambda itself.

Leave a ReplyCancel reply