c++ - const 方法中的非常量 lambda 捕获

标签 c++ lambda this c++17

#include <iostream>
#include <functional>

class Blub {
public:
    int i = 0;
    std::function<void()> create() const {
        return [this]() {
            this->i = 100;
        };
    }
};

int main() {
    Blub blub = Blub();
    blub.create()();
    std::cout << blub.i << std::endl;
    return 0;
}

我知道 this 在 lambda 中被捕获为 const,因为该方法被标记为 const。 除了删除方法的常量性之外,是否还有一种方法可以存档我可以修改 lambda 函数内的成员变量?

添加 mutable 关键字无效。

最佳答案

您可以将成员变量i声明为mutable,这样即使对象被声明为const它也可以改变:

class Blub {
public:
    mutable int i = 0;
//  ^^^^^^^
    std::function<void()> create() const {
        return [this]() {
            this->i = 100;
        };
    }
};

直播here .

关于c++ - const 方法中的非常量 lambda 捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60056637/

相关文章:

c++ - 方法/构造函数及其返回值

javascript - 从 Node.js Lambda 函数引用 CloudFormation 变量

javascript - 模拟不同选择器的点击事件

javascript - 包含 "this"关键字的方法在另一个方法中调用时与分配给局部变量时的工作方式不同

c++ - 共享指针的段错误

c++ - 使用线程传递指针时出错

c++11 - 嵌套的 lambda 捕获

c# - LINQ/Lambda 通过将列表项分成偶数组来更新列表项

c++ - 从另一个类对象调用常量函数

c++ - 函数指针模板参数个数