C ++ 17 Lambda捕获*此 [英] C++17 lambda capture *this
问题描述
C ++ 17将按值添加此对象的副本捕获,其中捕获规范为 [* this]
。
C++17 will add copy capture of this object by value, with a capture specification of [*this]
.
这有什么用?与捕获 this
有何不同?不能在C ++ 14中使用 [tmp = * this]
实现吗?
How is this useful? How is it different than capturing this
? Can't this already be achieved in C++14 with [tmp = *this]
?
奖金,用于解释为什么 P0018R3 使用 [=,tmp = * this]
代替 [tmp = * this]
在他们的例子中。如果他们使用 [tmp = * this]
,则将消除C ++ 14解决方案列出的所有缺点。
Bonus for explaining why P0018R3 uses [=, tmp = *this]
instead of [tmp = *this]
in their example. If they had used [tmp = *this]
, all the listed downsides of the C++14 solution would be eliminated.
推荐答案
它有什么用?当您需要 * this
的副本时非常有用-例如,当 * this
本身不再有效时,
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.
与捕获 this
有何不同?它创建对象的副本,以便在评估lambda时,其 this
指针指向副本,而不是原始对象。
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.
在C ++ 14中可以使用 [tmp = * this]
来实现吗?可以,但是 [* this]
更方便,因为可以在不使用 tmp前缀成员访问的情况下移动代码。
。否则,尤其是对于 [=,tmp = * this]
,当您要引用副本时,可能会意外地引用原始对象的成员(尤其是如果重新剪切/粘贴编程的习惯)。在这种情况下, [=,* this]
是一个更安全的选择,因为原始对象无法从lambda体内访问(至少不能通过 this
指针)。
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).
这篇关于C ++ 17 Lambda捕获*此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!