C++ lambda 按值语义捕获?

C++ lambda capture by value semantic?

class TestGetStr {
public:
    string a;
    string getString() {
        return a;
    }
};

void acceptConstString(const string & a) {
    std::cout << a << std::endl;
}

int main(int argc, const char * argv[]) {
    
    auto testGetStr = TestGetStr();

    acceptConstString(testGetStr.getString()); //compile ok

    auto testaaa = [testGetStr](){

//compile error 'this' argument to member function 'getString' has type 'const TestGetStr', but function is not marked const        
acceptConstString(testGetStr.getString());
    };
    

普通调用和lambda捕获的区别?

普通调用可以编译,lambda调用无法编译

为什么?感谢您提供更多详细信息。

您可以添加 mutable 限定符。

auto testaaa = [testGetStr]() mutable {
//                            ^^^^^^^
    acceptConstString(testGetStr.getString());
};

否则lambdaoperator()是const限定的,就不能在捕获对象上调用非常量成员函数了。

  • mutable: allows body to modify the objects captured by copy, and to call their non-const member functions

Unless the keyword mutable was used in the lambda-expression, the function-call operator is const-qualified and the objects that were captured by copy are non-modifiable from inside this operator().

PS:或者最好使 TestGetStr::getString() const 成员函数。