如何在lambda中按值捕获`this`和局部变量?

问题描述 投票:4回答:4

下面的lambda函数捕获this(因此bar()可以访问其实例变量)和局部变量a,b,c

class Foo
{
    int x, y, z;
    std::function<void(void)> _func;
    // ...
    void bar()
    {
        int a, b, c;
        // ...
        _func = [this, a, b, c]() // lambda func
        { 
            int u = this->x + a;
            // ...
        };
    }
};

但是,如果我想捕获许多实例变量,并希望避免在捕获列表中明确命名它们,我做到了[[not似乎可以做到这一点:

_func = [this, =]() // lambda func { // ... };
我在=之后的this,处遇到编译器错误:

error: expected variable name or 'this' in lambda capture list

如果我尝试这个

_func = [=,this]() // lambda func { // ... };

我知道

error: 'this' cannot be explicitly captured when the capture default is '='

是否存在用于按值捕获this和其他所有内容的捷径?
c++ class c++11 lambda this
4个回答
7
投票
正如cppreference所说:

[=]通过副本捕获lambda主体中使用的所有自动变量,并通过引用捕获当前对象使用的所有自动变量

3
投票
[=]已按值捕获this。看一下下面的实时代码:http://cpp.sh/87iw6

#include <iostream> #include <string> struct A { std::string text; auto printer() { return [=]() { std::cout << this->text << "\n"; }; } }; int main() { A a; auto printer = a.printer(); a.text = "Hello, world!"; printer(); }


3
投票
[=]做您想要的-它按值捕获非成员变量,按引用捕获*this(或按值捕获this的对象。)>

[*this,=]捕获两个局部变量

通过中的值捕获对象。[[&]按引用捕获局部变量,按引用捕获*this或按值捕获this(指针)。

两个默认捕获模式都以相同方式捕获this。您只能在中进行更改。


1
投票
[[=]将起作用,因为它会通过复制捕获lambda主体中使用的所有自动变量。
© www.soinside.com 2019 - 2024. All rights reserved.