I was a bit puzzled when I saw the following working
struct A {
void g(){}
void f(){
[&](){ g(); }();
}
};
but then I found this answer which explains in quite deep detail how that works.
In essence, it boils down to this is captured by value whether you use [=] or [&].
However, on cppreference I read the following
The current object
(*this)can be implicitly captured if either capture default is present. If implicitly captured, it is always captured by reference, even if the capture default is=.
So I have two formulations which seem to be equivalent
thisis captured by value whether we use[=]or[&].(*this)is captured by reference whether we use[=]or[&].
First of all, are indeed the two formulations above perfectly equivalent?
I do see a difference between the two, if not in what's practically possibile, at least in terms how useful they look.
Formulation 1 seem just weird to me. Why preventing me from capturing this by const-reference? Performance-wise there shouldn't be any big difference in the two cases, and I can always do auto const& This = this; before the lambda, and then capture This by reference, if I want to. As regards dangling references, if I'm using the this keyword, I'm in the object class, so how can the object die while I'm inside it?
Formulation 2, on the other hand, does seem to protect me from making unnecessary copies that would happen if (*this) was captured by value when using [=]. Furthermore, if I really want to, there's a capture syntax for capturing (*this) by copy, namely [*this].