C ++中lambda派生的隐式函子的生命周期是什么? [英] What is lifetime of lambda-derived implicit functors in C++?
问题描述
问题很简单:当我写一个lambda表达式时,什么是C ++编译器为我自动生成的functor对象的生命周期?
The question is simple: what is lifetime of that functor object that is automatically generated for me by the C++ compiler when I write a lambda-expression?
一个快速搜索,但找不到一个满意的答案。特别是,如果我通过lambda某处,它被记住在那里,然后我走出范围,一旦我的lambda被调用后会发生什么,并试图访问我的堆栈分配,但不再活着,捕获的变量?还是编译器以某种方式防止这种情况?或者什么?
I did a quick search, but couldn't find a satisfactory answer. In particular, if I pass the lambda somewhere, and it gets remembered there, and then I go out of scope, what's going to happen once my lambda is called later and tries to access my stack-allocated, but no longer alive, captured variables? Or does the compiler prevent such situation in some way? Or what?
推荐答案
取决于如何捕获变量。如果你通过引用捕获它们( [&]
),它们超出范围,引用将无效,就像正常引用一样。如果您想确保它们的作用范围,请按值( [=]
)捕获它们。
Depends on how you capture your variables. If you capture them by reference ([&]
) and they go out of scope, the references will be invalid, just like normal references. Capture them by value ([=]
) if you want to make sure they outlife their scope.
这篇关于C ++中lambda派生的隐式函子的生命周期是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!