How is it useful? It’s useful when you need a copy of *this
– for example, when *this
itself is no longer valid by the time the lambda is evaluated.
How is it different from capturing this
? It makes a copy of the object, so that when the lambda is evaluated, its this
pointer refers to the copy, rather than to the original object.
Can it be achieved in C++14 with [tmp = *this]
? It can, but [*this]
is more convenient, as code can be moved without prefixing member access with tmp.
. Otherwise, especially with [=, tmp = *this]
, it’s possible to accidentally refer to members of the original object when you meant to refer to the copy (particularly if you’re in the habit of cut+paste programming). [=,*this]
is a safer alternative in this case, as the original object is not accessible from inside the lambda’s body (at least, not via the this
pointer).