Home >Backend Development >C++ >Comparison of C++ function pointers and callback functions
Function pointers and callback functions are both tools for implementing the callback mechanism. Function pointers are created at compile time and cannot be modified and need to be called explicitly; callback functions are created at runtime and can be dynamically bound to different functions and automatically called by the callback function. Therefore, function pointers are suitable for static callbacks, while callback functions are suitable for dynamic callbacks.
Function pointers and callback functions are both powerful tools used to implement the callback mechanism in C.
Function pointer
Callback function
Consider an application that needs to perform different tasks at different times. We can achieve this functionality using the following code:
#include <iostream> // 定义一个打印消息的函数 void print_message(const char* message) { std::cout << message << std::endl; } // 定义一个接受函数指针参数的回调函数 void execute_callback(void (*callback)(const char*)) { callback("Hello world!"); } int main() { // 使用函数指针调用回调函数 execute_callback(print_message); // 动态创建并调用回调函数 auto lambda = [](const char* message) { std::cout << "[Lambda] " << message << std::endl; }; execute_callback(lambda); return 0; }
In this example, print_message
is a function pointer for static callbacks. A lambda expression lambda
is a dynamic callback that is created at runtime and bound to execute_callback
.
Features | Function pointer | Callback function |
---|---|---|
Creation timing | Compile time | Run time |
Unmodifiable | Can be modified | |
Explicit | Automatic | |
static | dynamic |
The above is the detailed content of Comparison of C++ function pointers and callback functions. For more information, please follow other related articles on the PHP Chinese website!