함수 포인터와 callback
Callback은 algorithm이 caller가 정한 동작을 호출하게 합니다.
함수 포인터와 callback이란?
Callback은 algorithm이 caller가 정한 동작을 호출하게 합니다.
다른 함수로 behavior를 전달합니다.
중요한 점
- 포인터는 살아 있는 호환 객체를 가리키거나 null이어야 합니다.
- 소유한 allocation은 정확히 한 번 해제하세요.
- Ownership과 const를 명확히 표현하세요.
C와 C++ 코드 예제
C
main.c
#include <stdio.h>
int square(int value) { return value * value; }
int apply(int value, int (*operation)(int)) { return operation(value); }
int main(void) {
printf("%d\n", apply(6, square));
return 0;
}
36
C++
main.cpp
#include <functional>
#include <iostream>
int apply(int value, const std::function<int(int)>& operation) {
return operation(value);
}
int main() {
int factor = 6;
std::cout << apply(factor, [](int value) { return value * value; }) << '\n';
}
36
C와 C++ 비교
C는 명시적 function pointer type을 쓰고 C++는 상태를 가진 lambda와 std::function도 사용합니다.
C
Ownership과 cleanup은 개발자가 지켜야 하는 규칙입니다.
C++
Container와 RAII가 ownership과 cleanup을 lifetime에 연결합니다.
연습 문제
두 버전을 실행하고 수정하여 각 언어의 보장을 관찰하세요.
- null과 할당 실패를 테스트하세요.
- AddressSanitizer와 UndefinedBehaviorSanitizer를 실행하세요.
- 각 pointer의 ownership을 문서화하세요.