C++ Lambda와 C closure 방식
Lambda는 capture 가능한 익명 callable을 만들고 C는 context를 명시적으로 넘깁니다.
C++ Lambda와 C closure 방식이란?
Lambda는 capture 가능한 익명 callable을 만들고 C는 context를 명시적으로 넘깁니다.
Callback에 context를 전달합니다.
중요한 점
- 먼저 C 메커니즘을 이해하세요.
- RAII와 value semantics로 ownership을 표현하세요.
- Macro와 cast보다 type-safe 추상화를 사용하세요.
C와 C++ 코드 예제
C
main.c
#include <stdio.h>
int above(int value, void *context) {
return value > *(int *)context;
}
int main(void) {
int values[] = {2, 7, 4, 9};
int threshold = 5;
int count = 0;
for (int index = 0; index < 4; ++index) {
count += above(values[index], &threshold);
}
printf("%d\n", count);
}
2
C++
main.cpp
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector values{2, 7, 4, 9};
int threshold = 5;
auto above = [threshold](int value) {
return value > threshold;
};
std::cout << std::count_if(values.begin(), values.end(), above)
<< '\n';
}
2
C와 C++ 비교
C 함수는 void*를 cast합니다. C++ lambda는 threshold를 value capture해 type 정보를 유지합니다.
C
C는 prefix, callback, macro와 context 구조를 씁니다.
C++
언어 기능이 scope와 type safety를 갖춘 추상화를 제공합니다.
연습 문제
두 버전을 실행하고 수정하여 각 언어의 보장을 관찰하세요.
- C 메커니즘을 먼저 작성하세요.
- 수동 cleanup을 RAII로 바꾸세요.
- Allocation과 virtual dispatch를 확인하세요.