LoginSignup
0
0

More than 1 year has passed since last update.

【C++】 Lambda関数のimmutableとは?

Last updated at Posted at 2022-10-28

Lambda関数のImmutableについて

公式ドキュメントでLambda関数はdefaultで引数がImmutable(不変)と書いてあったがよく分からなかったので、実際に試してみました。

  • []の中の値がキャプチャと呼ばれていて、以下のようなCopyキャプチャは変数を変更不可能(Const)らしいですね。
    int x = 100;
    auto hoge = [x]() {
      x = 3; // compilation error
    };
    hoge();
  • ()の中の値がパラメーターと呼ばれていて、普通の関数同様に変数xに値を代入できます。
    auto hoge = [](int x) {
      x = 3;
    };
    int num = 100;
    hoge(num);
  • 普通の関数同様にconstをつければちゃんとerrorを吐いてくれます。
    auto hoge = [](const int x) {
      x = 3; //compilation error
    };
    int num = 100;
    hoge(num);

まとめ

書き方によって挙動が違うのは分かりづらいですね。やっぱり引数にconstが付いていると安心できます。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0