关于默认捕获模式的限制和'this'在C ++ lambda表达式 [英] restriction about default capture mode and 'this' in C++ lambda-expression
问题描述
我想知道为什么 =
capture-default 模式禁止
I'm wondering why =
capture-default mode prohibits this
in capture-list of C++ lambda expression.
也就是说,
[=, this]{ }; // error
[&, this]{ }; // OK
这是由C ++ 11 5.1.2 / 8指定的
This is specified by C++11 5.1.2/8.
- 如果lambda捕获包括一个捕获默认是&,
标识符在lambda-捕获不应在&。之前。
- 如果lambda捕获包含一个捕获默认值为=,
lambda捕获不应包含此和每个标识符包含
前应加上&。
问:这个规则的背景故事?
Q: Is there any reason or background story for this rule?
推荐答案
复制和从不通过引用。即使只指定
[&]
,,也可以通过copy来隐式捕获
。因此, [=,this]
是一个错误,因为 =
已经隐式捕获 / code>,而
[& this,]
中的&
表示通过引用捕获,不会隐式捕获此
(除非是使用odr)
this
can only be captured by copy and never by reference. Even if you specify only [&]
, this
can be implicitly captured by copy if odr-used. Therefore, [=, this]
is an error because =
would already implicitly capture this
by copy while the &
in [&, this]
signifies capture by reference and does not implicitly capture this
(unless it is odr-used)
这篇关于关于默认捕获模式的限制和'this'在C ++ lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!