Home > Net >  What the meaning of mark a lambda capturing this as mutable in C ?
What the meaning of mark a lambda capturing this as mutable in C ?

Time:09-06

I found following code in a raft implementation.

[this](ptr<resp_msg>& resp, const ptr<rpc_exception>& e) mutable {
          this->handle_peer_resp(resp, e);
}

When we capture this in a lambda expression, we have already be allowed to modify the value of member or call member function (as shown following).

#include <functional>
#include <iostream>

class A {
public:
  int a;
  A() { a = 0; }
  std::function<void(int)> func = [this](const int & b) mutable { a = 10; this->print(b); };
  void callFunc() { func(1); }

  void print(const int & b) { std::cout << a << " " << b << std::endl; }
};

int main() {
  A a;
  a.callFunc();
  return 0;
}

Why do they use mutable in this lambda function ?

CodePudding user response:

In this

std::function<void(int)> func = [this](const int & b) mutable {
    a = 10;
    this->print(b);
};

there is nothing mutating the lambda and removing mutable would be the reasonable thing to do.

CodePudding user response:

well, after digging it little bit, this is what I found on Microsoft Documentations:

The mutable keyword is used so that the body of the lambda expression can modify its copies of the external variables x and y, which the lambda expression captures by value. Because the lambda expression captures the original variables x and y by value, their values remain 1 after the lambda executes.

so basically marking a lambda expression as mutable allows it to access and mutate "change" the external variables if needed.

CodePudding user response:

it should be a historical issue, this code has been refactored couple times, and mutable looks not necessary now, can you submit a pr for this?

  •  Tags:  
  • c
  • Related