gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:44:47 27 4
gpt4 key购买 nike

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

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 beginningwith 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 ofthe lambda by reference

[=] captures all automatic variables odr-usedin the body of the lambda by value

[] captures nothing

这意味着只会捕获 lambda 主体中使用的自动(作用域生命周期)变量。

我不明白为什么用 [&] 捕获所有内容会比单独捕获更昂贵,但是明确列出捕获的一个好处是没有机会捕获你没有捕获的东西'没想到。

另一方面,使用 [=] 捕获可能会很昂贵,因为它会复制所有内容。也许这就是您的同事所指的。

关于c++ - C++11 lambda 捕获实际捕获了多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37126369/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com