【C++】ラムダ式でメンバ変数をキャプチャする

メモ。

メンバ関数内でラムダ式を使う時、メンバ変数をキャプチャするにはthisをキャプチャする。

struct Hoge {
  int n;
  void f() {
    auto lambda = [this]() -> int {  // this をキャプチャ
      return n * 2;                  // メンバ n を使う
    }
    std::cout << lambda() << std::endl;
  }
};

[&]で全オブジェクトを参照キャプチャしてもthisは含まれる。