関数ポインタとcallback
Callbackによりalgorithmはcallerが選んだbehaviorを呼び出せます。
関数ポインタと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型を使い、C++は状態を持つlambdaやstd::functionも利用できます。
C
ownershipとcleanupはプログラマが守る規約です。
C++
containerとRAIIがownershipとcleanupをlifetimeに結び付けます。
練習課題
両方を実行して変更し、言語ごとの保証を確認します。
- nullとallocation失敗をテストします。
- AddressSanitizerとUndefinedBehaviorSanitizerを使います。
- 各pointerのownershipを文書化します。