11.9 Lambda captures

주홍영·2022년 3월 14일
0

Learncpp.com

목록 보기
123/199

https://www.learncpp.com/cpp-tutorial/lambda-captures/

람다식의 형태는 다음과 같았다

[ captureClause ] ( parameters ) -> returnType
{
    statements;
}

capture clause는 lambda의 scope로 외부 scope의 변수를 가져올 수 있는 수단이다
본래 외부 변수는 parameter로 전달 받지만
그것을 떠나서 현재 lambda식이 사용되는 scope에서 접근할 수 있는 변수를
사용하기 위해서 capture clause 사이에 작성하여 접근이 가능하도록 하는 것이다

이때 복수의 variable에 접근하고 싶으면 multiple로 가져와도 된다

int health{ 33 };
int armor{ 100 };
std::vector<CEnemy> enemies{};

// Capture health and armor by value, and enemies by reference.
[health, armor, &enemies](){};

또한 capture은 본디 pass by value이므로 만약
원본을 수정하고 싶으면 pass by reference로 선언해줘야 한다
만약 pass by value인 경우에는

#include <iostream>

int main()
{
  int ammo{ 10 };

  auto shoot{
    // Added mutable after the parameter list.
    [ammo]() mutable {
      // We're allowed to modify ammo now
      --ammo;

      std::cout << "Pew! " << ammo << " shot(s) left.\n";
    }
  };

  shoot();
  shoot();

  std::cout << ammo << " shot(s) left\n";

  return 0;
}

output

Pew! 9 shot(s) left.
Pew! 8 shot(s) left.
10 shot(s) left

위에서 9, 8이 나온거는 auto shoot이라는 variable안에 ammo라는 것이 pass by value로
새로 instantiate 되었기 때문에 , shoot::ammo가 1씩 줄어든 것이다
사실 우리는 main scope의 ammo에 접근하고 싶었던 것이다

#include <iostream>

int main()
{
  int ammo{ 10 };

  auto shoot{
    // We don't need mutable anymore
    [&ammo]() { // &ammo means ammo is captured by reference
      // Changes to ammo will affect main's ammo
      --ammo;

      std::cout << "Pew! " << ammo << " shot(s) left.\n";
    }
  };

  shoot();

  std::cout << ammo << " shot(s) left\n";

  return 0;
}

output

Pew! 9 shot(s) left.
9 shot(s) left

위와같이 &ammo를 capture clause에 넣어주면 pass by ref로 원본에 접근해 조작할 수 있다

그외에 많은 내용이 있지만 모두 다루기에는 무리가 있다고 판단 생략한다

profile
청룡동거주민

0개의 댓글