繁体   English   中英

由 lambda function (C++) 捕获的局部变量的 scope

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

我到处搜索,但找不到我的问题的答案。 我正在尝试编写一个示例,该示例显示通过引用捕获封闭 function 的局部变量是危险的,因为它在实际引用时可能不再存在。 这是我的例子:

#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;
}

我试图通过从test2返回 lambda function 来访问和修改堆栈帧上不存在的局部变量来重现堆栈损坏,该 test2 捕获局部变量k并修改它。

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

打印出一个垃圾值,表明出现了预期的问题。 然而,

test(test2(100));

打印出“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 . 我会很感激我可以用来搜索答案的任何想法或关键字。

我已经在我的机器上运行了你的测试,结果在这两种情况下都是预期的总垃圾。 以这种身份偶尔有一个正确的答案是非常具有误导性的。 只要指向的 memory 尚未被不同的值占用,悬空引用或指针可能偶尔会指向相同的值。

简而言之,C++ lambda 不会延长捕获的引用/指针的生命周期,因为它们的引用堆栈会展开。 同样的事情也适用于捕获 class 的“this”指针。 如果 class 超出 scope,则“this->”将导致完全未定义的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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