What is lifetime of lambda-derived implicit functo

2020-02-28 05:17发布

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?

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?

标签: c++ lambda
1条回答
Luminary・发光体
2楼-- · 2020-02-28 05:43

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.

查看更多
登录 后发表回答