c++ - C++11 lambda 捕获实际捕获了多少?

标签 c++ performance c++11 lambda

我在多个示例中看到您可以使用单个字符来捕获多个变量,如下所示:

Rect rect;
Point point;

auto someLambda = [&](const SomeType& var)
{
    if (rect.Contains(point))
    {
        var.Something();
    }

    this->MemberFunction();
};

这最终会通过引用获取 rectpoint 并且还可以让您访问 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/

相关文章:

r - 提高 R 的效率(矢量化?)

c++ - 推导给定参数类型的选定重载函数类型

c++ - 来自另一个类的对象的类 vector

c++ - 如何只允许对像对象这样的整数有效值并对其进行迭代?

algorithm - Stein 算法的最坏情况输入是什么?

c++ - 分支预测 vs 分支目标预测

支持三值逻辑的 C++ 库 : 0, 1,X

c++ - std::count 错误

c++11 - 完美转发 - 这是怎么回事?

c++11 - SIGINT 未在此范围内声明