我在多个示例中看到您可以使用单个字符来捕获多个变量,如下所示:
Rect rect;
Point point;
auto someLambda = [&](const SomeType& var)
{
if (rect.Contains(point))
{
var.Something();
}
this->MemberFunction();
};
这最终会通过引用获取 rect
和 point
并且还可以让您访问 this
,但它实际捕获了多少?它只捕获它需要的变量,还是捕获当前范围内的所有内容?
我在其他示例中看到,您还可以像这样指定要捕获的单个变量:
Rect rect;
Point point;
auto someLambda = [this, &rect, &point](const SomeType& var)
{
if (rect.Contains(point))
{
var.Something();
}
this->MemberFunction();
};
以这种或另一种方式做有什么好处吗?与我共事的人曾经提到使用“捕获所有”[&]
版本更昂贵,但我找不到任何文档来支持它。我只是想确定地知道,所以我不会让代码变得比它需要的更复杂,也不会做我不应该做的昂贵的事情。
最佳答案
根据 http://en.cppreference.com/w/cpp/language/lambda ,捕获列表(方括号中的部分)为:
a comma-separated list of zero or more captures, optionally beginning with a capture-default. Capture list can be passed as follows [...]:
[a,&b] where a is captured by value and b is captured by reference.
[this] captures the this pointer by value
[&] captures all automatic variables odr-used in the body of the lambda by reference
[=] captures all automatic variables odr-used in the body of the lambda by value
[] captures nothing
这意味着只会捕获 lambda 主体中使用的自动(作用域生命周期)变量。
我不明白为什么用 [&]
捕获所有内容会比单独捕获更昂贵,但是明确列出捕获的一个好处是没有机会捕获你没有捕获的东西'没想到。
另一方面,使用 [=]
捕获可能会很昂贵,因为它会复制所有内容。也许这就是您的同事所指的。
关于c++ - C++11 lambda 捕获实际捕获了多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37126369/