x
,尽管:
- 捕获列表是空的,即没有捕获默认值
- 注释说它“不会捕获
x
”
以下是示例:
void f(int, const int (&)[2] = {}) { } // #1
void test() {
const int x = 17;
auto g = [](auto a) {
f(x); // OK: calls #1, does not capture x
};
}
请看它可以编译。这似乎取决于x
是const
;如果删除const
,则由于捕获列表为空而不再编译。即使我使参数成为int
,使其不再是通用lambda,它仍然会发生。
即使捕获列表为空,lambda如何引用x
?而且在同时显然没有捕获x
的情况下,这是如何实现的(正如注释所说)?
关于此主题,我找到的最接近的东西是其他人在评论中间接地注意到了这一点。
以下是标准的完整部分5.1.2/12:
A lambda-expression with an associated capture-default that does not explicitly capture
this
or a variable with automatic storage duration (this excludes any id-expression that has been found to refer to an init-capture’s associated non-static data member), is said to implicitly capture the entity (i.e.,this
or a variable) if the compound-statement:
- odr-uses (3.2) the entity, or
- names the entity in a potentially-evaluated expression (3.2) where the enclosing full-expression depends on a generic lambda parameter declared within the reaching scope of the lambda-expression.
[ Example:
void f(int, const int (&)[2] = {}) { } // #1 void f(const int&, const int (&)[1]) { } // #2 void test() { const int x = 17; auto g = [](auto a) { f(x); // OK: calls #1, does not capture x }; auto g2 = [=](auto a) { int selector[sizeof(a) == 1 ? 1 : 2]{}; f(x, selector); // OK: is a dependent expression, so captures x }; }
—end example ] All such implicitly captured entities shall be declared within the reaching scope of the lambda expression. [ Note: The implicit capture of an entity by a nested lambda-expression can cause its implicit capture by the containing lambda-expression (see below). Implicit odr-uses of this can result in implicit capture. —end note ]
&
时,你正在获取它的地址,因此编译器需要为变量分配存储空间。 - Jesse Good