在c++ lambda表达式中调用类成员函数失败.处理步骤

Failed to call class member function in C++ lambda expression

本文关键字:失败 函数 处理 成员 lambda c++ 表达式 调用      更新时间:2023-10-16
//==== 1 ====
string func1(string x1, string x2){
    return x1 + x2;
}
auto lambda1 = [](string x1, string x2){cout << func1(x1,x2);};
//==== 2 ====
class Test{
public:
    string func2(string x1, string x2){
        return x1 + x2;
    }
    void tst(){
        auto lambda2 = [](string x1, string x2){cout << func2(x1,x2);};
    }
};

lambda1是正确的。但是lambda2得到了一个错误(在g++ 4.8下):

error: 'this' was not captured for this lambda function
         auto lambda2 = [](string x1, string x2){cout << func2(x1,x2);};

在lambda中调用成员函数的正确方法是什么?

编译器给出您正在寻找的答案:

错误:'this'未捕获此lambda函数

您需要在[]括号内提供this捕获:

auto lambda2 = [this](string x1, string x2){cout << func2(x1,x2);};

如果没有它,编译器将不知道变量的上下文。注意,x1x2都将被复制。

在这里阅读更多关于lambda捕获的信息

Test::tst()下的lambda函数中,您有对func2的调用。该调用不能完成,除非thislambda函数捕获。

void tst(){
    auto lambda2 = [this](string x1, string x2){cout << this->func2(x1,x2);};
}