C++ lambda 按值语义捕获?

标签 c++ lambda constants

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 成员函数。

关于C++ lambda 按值语义捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66526702/

相关文章:

c# - 表达式树是线程安全的吗?

c - const 说明符在 cast 中的必要性

c++ - extern const 数组不链接

c++ - 如何可移植(反)序列化 qint32?

c++ - 为什么 std::equal_to 会导致动态分配?

lambda - 如何在 LISP 中定义 LAMBDA 函数?

mysql - 在 RDS 中访问 MySQL 或 MS SQL 时,AWS Lambda node.js ETIMEDOUT

java - 如何获取在类中声明为映射的常量

c++ - 如何操作这个界面?

c++ - 从 Python 脚本控制 C++ 输出