简体   繁体   中英

The scope of local variables captured by a lambda function (C++)

I searched everywhere but could not find an answer to my question. I am trying to write an example that shows that capturing a local variable of the enclosing function by reference is dangerous because it may not exist anymore when it is actually referenced. Here's my example:

#include <iostream>


std::function<int (int)> test2(int l) {
       int k = 10;
       return [&] (int y) { return ++k + 100; };
}


void test(std::function<int (int)> k) {
        std::cout << k(100);
}

int main() {
        test(test2(100));

        std::function<int (int)> func = test2(100);
        test(func);

        return 0;
}

I tried to reproduce stack corruption from trying to access and modify a local variable that doesn't exist on the stack frame by returning a lambda function from test2 that captures a local variable k and modifies it.

std::function<int (int)> func = test2(100);
test(func);

prints out a garbage value which indicates something went wrong as expected. However,

test(test2(100));

prints out "111". This is confusing to me as I thought when test2(100) returns a lambda function of type std::function, the stack frame for test2 will be gone, and when test is invoked, it should not be able to access the value of k. I'd appreciate any ideas or keywords I can use to search for answers.

I have run your test on my machine and the results are as expected total garbage in both cases. Having a correct answer once in a while in this capacity is very misleading. A dangling reference or pointer might occasionally point out to the same value as long as the pointed memory hasn't been occupied by a different value yet.

In a nutshell, The C++ lambdas do not extend the lifetimes of captured references/pointers shall their reference stack unwind. Same thing applies to capturing the 'this' pointer of a class. If the class goes out of scope, the 'this->' will result in a completely undefined behaviour.

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