• Source
    1. #include <iostream>
    2. #include <memory>
    3. #include <functional>
    4. using namespace std;
    5.  
    6.  
    7. int main() {
    8. // [] 内に変数名を書くと、無名関数外の変数をコピーして持ってこれる
    9. string str = "Hoge";
    10. [str]() {
    11. cout << str << endl;
    12. }();
    13. cout << "-----" << endl;
    14.  
    15. // そのままだと内容が変更できないが、mutable と記述すると変更できる。
    16. [str]() mutable {
    17. str = "Fuga";
    18. cout << str << endl;
    19. }();
    20. cout << "-----" << endl;
    21.  
    22. // キャプチャに & をつけると参照キャプチャになる。
    23. // 参照なので元の変数に影響を与えられる。
    24. string strA = "AAA";
    25. string strB = "BBB";
    26. [strA, &strB]() mutable {
    27. cout << "strA:" << strA << endl;
    28. cout << "strB:" << strB << endl;
    29. cout << "-----" << endl;
    30.  
    31. strA = "ZZZ";
    32. strB = "ZZZ";
    33.  
    34. // 無名関数内では strA, strB 共に変更が起こる。
    35. cout << "strA:" << strA << endl;
    36. cout << "strB:" << strB << endl;
    37. cout << "-----" << endl;
    38. }();
    39.  
    40. // 参照キャプチャした strB のみ影響が残る
    41. cout << "strA:" << strA << endl;
    42. cout << "strB:" << strB << endl;
    43.  
    44. return 0;
    45. }