【问题标题】:C++ lambda capture by value semantic? [duplicate]C ++ lambda按值语义捕获? [复制]
【发布时间】:2021-03-08 08:47:43
【问题描述】:
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调用不能编译。

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

【问题讨论】:

  • Lambda 默认为const。您需要将其显式标记为mutable - auto testaaa = [testGetStr]() mutable {...}。或者,最好将getString() 标记为const

标签: c++ lambda constants


【解决方案1】:

您可以添加mutable 限定符。

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

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

  • mutable:允许body修改copy捕获的对象,并调用它们的非常量成员函数

除非在 lambda 表达式中使用关键字 mutable,否则 函数调用运算符是 const 限定的,并且对象是 无法从 operator() 内部修改通过副本捕获的内容。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    相关资源
    最近更新 更多