Is this behaviour specified by the standard
Yes. Capturing member variables is always done via capturing this
; it is the only way to access a member variable. In the scope of a member function a_
is equivalent to (*this).a_
. This is true in Lambdas as well.
Therefore, if you use this
(implicitly or explicitly), then you must ensure that the object remains alive while the lambda instance is around.
If you want to capture it by value, you must explicitly do so:
std::function<void()> getf()
{
auto varA = a_;
return [=]() { varA->a(); };
}
If you need a spec quote:
The lambda-expression’s compound-statement yields the function-body ( 8.4 ) of the function call operator, but for purposes of name lookup (3.4), determining the type and value of this (9.3.2) and transforming id-expressions referring to non-static class members into class member access expressions using (*this) ( 9.3.1 ),
the compound-statement is considered in the context of the lambda-expression.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…