Function Pointers और Callbacks
Callback algorithm को caller द्वारा चुनी logic invoke करने देता है।
Function Pointers और Callbacks क्या है?
Callback algorithm को caller द्वारा चुनी logic invoke करने देता है।
Behavior दूसरे function को पास करें।
महत्वपूर्ण बातें
- Pointer किसी जीवित compatible object को point करे या null हो।
- हर owned allocation को ठीक एक बार release करें।
- Ownership और const interfaces स्पष्ट रखें।
C और C++ code examples
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 explicit function pointer type उपयोग करता है; C++ state वाले lambdas और std::function भी देता है।
C
Ownership और cleanup programmer द्वारा लागू conventions हैं।
C++
Containers और RAII ownership को object lifetime से जोड़ते हैं।
अभ्यास
दोनों versions चलाकर बदलें और language guarantees की तुलना करें।
- Null और allocation failure paths test करें।
- AddressSanitizer और UndefinedBehaviorSanitizer चलाएँ।
- हर pointer का ownership लिखें।