C++ 람다 함수 | "익명 함수" 완벽 정리 [캡처/mutable]

C++ 람다 함수 | "익명 함수" 완벽 정리 [캡처/mutable]

이 글의 핵심

C++ 람다 함수에 대한 실전 가이드입니다.

기본 문법

STL 알고리즘과 비동기 콜백에서 짧은 함수 로직을 한곳에 두고 싶을 때 람다가 유용합니다. 이 글에서는 캡처 목록과 반환 타입을 어떻게 고르는지, 이후 절의 문법·캡처 예제를 순서대로 따라가며 익힐 수 있습니다.

// 기본 형태
auto lambda =  {
    cout << "Hello Lambda!" << endl;
};

lambda();  // 호출

// 매개변수와 반환값
auto add =  -> int {
    return a + b;
};

cout << add(3, 5) << endl;  // 8

// 반환 타입 자동 추론
auto multiply =  {
    return a * b;  // int 자동 추론
};

캡처 (Capture)

값 캡처

int x = 10;
int y = 20;

// 값으로 캡처
auto lambda1 = [x, y]() {
    cout << x + y << endl;
};

// 모든 변수를 값으로 캡처
auto lambda2 = [=]() {
    cout << x + y << endl;
};

참조 캡처

int count = 0;

// 참조로 캡처
auto increment = [&count]() {
    count++;
};

increment();
cout << count << endl;  // 1

// 모든 변수를 참조로 캡처
auto lambda = [&]() {
    count++;
};

혼합 캡처

int x = 10;
int y = 20;

// x는 값, y는 참조
auto lambda = [x, &y]() {
    y = x + 5;
};

lambda();
cout << y << endl;  // 15

mutable 람다

int x = 10;

// 값 캡처는 기본적으로 const
auto lambda1 = [x]() {
    // x++;  // 에러! const
};

// mutable로 수정 가능
auto lambda2 = [x]() mutable {
    x++;  // OK (복사본 수정)
    cout << x << endl;
};

lambda2();  // 11
cout << x << endl;  // 10 (원본은 변경 안됨)

실전 예시

예시 1: STL 알고리즘과 람다

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    // 짝수만 필터링
    auto it = remove_if(numbers.begin(), numbers.end(),  {
        return x % 2 != 0;
    });
    numbers.erase(it, numbers.end());
    
    // 출력
    for_each(numbers.begin(), numbers.end(),  {
        cout << x << " ";
    });
    cout << endl;  // 2 4 6 8 10
    
    // 정렬 (내림차순)
    sort(numbers.begin(), numbers.end(),  {
        return a > b;
    });
    
    // 조건 체크
    bool allEven = all_of(numbers.begin(), numbers.end(),  {
        return x % 2 == 0;
    });
    cout << "모두 짝수: " << allEven << endl;  // 1
    
    return 0;
}

설명: 람다를 사용하면 간단한 로직을 별도 함수 없이 인라인으로 작성할 수 있습니다.

예시 2: 이벤트 핸들러

#include <iostream>
#include <vector>
#include <functional>
using namespace std;

class Button {
private:
    string label;
    function<void()> onClick;
    
public:
    Button(string l) : label(l) {}
    
    void setOnClick(function<void()> handler) {
        onClick = handler;
    }
    
    void click() {
        cout << label << " 클릭!" << endl;
        if (onClick) {
            onClick();
        }
    }
};

int main() {
    int clickCount = 0;
    
    Button btn1("버튼1");
    btn1.setOnClick([&clickCount]() {
        clickCount++;
        cout << "클릭 횟수: " << clickCount << endl;
    });
    
    Button btn2("버튼2");
    btn2.setOnClick( {
        cout << "버튼2가 클릭되었습니다!" << endl;
    });
    
    btn1.click();
    btn1.click();
    btn2.click();
    
    return 0;
}

설명: 람다로 이벤트 핸들러를 간결하게 등록할 수 있습니다.

예시 3: 제네릭 람다 (C++14)

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    // auto 매개변수 (제네릭 람다)
    auto print =  {
        cout << x << endl;
    };
    
    print(10);           // int
    print(3.14);         // double
    print("Hello");      // const char*
    
    // 제네릭 람다로 다양한 타입 처리
    auto add =  {
        return a + b;
    };
    
    cout << add(1, 2) << endl;           // 3
    cout << add(1.5, 2.5) << endl;       // 4.0
    cout << add(string("Hello"), string(" World")) << endl;  // Hello World
    
    // 벡터 출력 (제네릭)
    auto printVector =  {
        for (const auto& item : vec) {
            cout << item << " ";
        }
        cout << endl;
    };
    
    vector<int> v1 = {1, 2, 3};
    vector<string> v2 = {"a", "b", "c"};
    
    printVector(v1);  // 1 2 3
    printVector(v2);  // a b c
    
    return 0;
}

설명: C++14부터 auto 매개변수로 제네릭 람다를 만들 수 있습니다.

자주 발생하는 문제

문제 1: 댕글링 참조

증상: 람다 실행 시 크래시 또는 이상한 값

원인: 참조 캡처한 변수가 이미 소멸됨

해결법:

// ❌ 위험한 코드
function<void()> makeCounter() {
    int count = 0;
    return [&count]() {  // 댕글링 참조!
        count++;
        cout << count << endl;
    };
}

auto counter = makeCounter();
counter();  // 크래시 또는 이상한 값

// ✅ 값으로 캡처
function<void()> makeCounter() {
    int count = 0;
    return [count]() mutable {
        count++;
        cout << count << endl;
    };
}

문제 2: this 캡처

증상: 멤버 변수 접근 불가

원인: this 캡처 누락

해결법:

class Counter {
private:
    int count = 0;
    
public:
    void increment() {
        // ❌ 에러
        auto lambda1 =  {
            count++;  // 에러! this 캡처 안됨
        };
        
        // ✅ this 캡처
        auto lambda2 = [this]() {
            count++;  // OK
        };
        
        // ✅ C++17: *this로 복사
        auto lambda3 = [*this]() mutable {
            count++;  // 복사본 수정
        };
    }
};

문제 3: 캡처 초기화 (C++14)

증상: 복잡한 초기화 불가

원인: 단순 캡처만 가능

해결법:

// ❌ C++11에서는 불가
unique_ptr<int> ptr = make_unique<int>(10);
auto lambda = [ptr]() {  // 에러! unique_ptr 복사 불가
    cout << *ptr << endl;
};

// ✅ C++14: 초기화 캡처
unique_ptr<int> ptr = make_unique<int>(10);
auto lambda = [ptr = move(ptr)]() {
    cout << *ptr << endl;
};

FAQ

Q1: 람다는 언제 사용하나요?

A:

  • STL 알고리즘의 조건자
  • 이벤트 핸들러
  • 콜백 함수
  • 간단한 일회용 함수

Q2: 람다 vs 함수 포인터?

A: 람다가 더 유연하고 캡처가 가능합니다. 함수 포인터는 캡처가 없는 람다로만 변환됩니다.

Q3: 람다의 타입은?

A: 각 람다는 고유한 타입을 가집니다. autofunction<>으로 저장합니다.

Q4: 재귀 람다는?

A: C++14부터 가능합니다.

function<int(int)> factorial = [&factorial](int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
};

Q5: 람다는 성능에 영향을 주나요?

A: 인라인화되면 오버헤드가 거의 없습니다. 일반 함수와 동일한 성능입니다.

Q6: 캡처 기본값은?

A:

  • [=]: 모두 값으로 (권장하지 않음, 명시적으로 캡처하세요)
  • [&]: 모두 참조로 (주의: 댕글링 참조 위험)
  • []: 캡처 없음 (가장 안전)

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ 람다 캡처 | “Lambda Capture” 완벽 가이드
  • C++ 람다 기초 완벽 가이드 | 캡처·mutable·제네릭 람다와 실전 패턴
  • C++ Init Capture | “초기화 캡처” 가이드

관련 글

  • C++ std::function vs 함수 포인터 |
  • C++ 람다 캡처 에러 |
  • C++ 람다 캡처 |
  • C++ async & launch |
  • C++ Atomic Operations |