Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading