如果我通过调用 fun1()
赋值,lambda 之外的 x 变量将被破坏(无法读取内存),但如果我运行 fun2()
一切都是好的。为什么?指针的拷贝仍然指向同一个东西,对吗?那为什么 fun1() 不起作用呢?
int *x = NULL;
auto fun1 = [x]() mutable
{
x = new int(5);
};
auto fun2 = [&x]()
{
x = new int(5);
};
最佳答案
auto fun1 = [x]() mutable { ... }
通过拷贝捕获x
,因此它修改了x
的拷贝。当 lamdba 返回时,您的 x
仍未分配。
auto fun2 = [&x]() { ... }
通过引用捕获 x
,因此您确实在修改 x
。
这与 lambda 无关:常规函数存在相同的行为 (see value and reference semantics entry in the C++ FAQ )
关于c++通过值或引用在lambda内部分配指针值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25444161/