yohhoyの日記

技術的メモをしていきたい日記

ラムダ式のcapture-defaultとthisポインタ

C++ラムダ式のキャプチャ指定において、デフォルトでコピーキャプチャ+thisポインタ[=, this]はNGだが、デフォルトで参照キャプチャ+thisポインタ[&, this]は許容される。*1

2018-07-03追記:C++2a(C++20)言語仕様としてP0806R2が採択され、[=]による暗黙のthisポインタキャプチャは非推奨(deprecated)となることが決定した。C++2a以降では[=, this]明示指定が推奨される。

2017-07-18追記:C++2a(C++20)言語仕様としてP0409R2が採択され、[=, this]もwell-definedとなることが決定した。セマンティクス上は単に[=]と等価に振る舞う。

// C++11
struct X {
  void mf() {
    //...
    auto a = [=, this]{ ... };  // NG: ill-formed
    auto b = [&, this]{ ... };  // OK
  }
};

N3337 5.1.2/p8より一部引用。

If a lambda-capture includes a capture-default that is &, the identifiers in the lambda-capture shall not be preceded by &. If a lambda-capture includes a capture-default that is =, the lambda-capture shall not contain this and each identifier it contains shall be preceded by &. (snip)

メモ:前者は「既定でコピー+明示的に変数コピー指定」なのでNG、後者は「既定で参照、明示的に変数コピー指定」なのでOKと考えれば当然か…。逆の[=, &this]ではthisがprvalueであるため(9.3.2/p1)、そもそもアドレスを取ることができない(5.3.1/p3)。

関連URL

*1:余談:第5回 C++オンライン読書会のときに、C++Now! 2012資料スライドを読んでいて疑問に思ったコト。