Use std::function, Unless There's a Compelling Reason Not To
When working with callback functions in C , the choice between using a C-style function pointer and the newer std::function can be a matter of debate. Let's examine the pros and cons of each option.
C-Style Function Pointers:
std::function:
When to Use std::function:
In most cases, std::function is the preferred choice. It's more flexible and future-proof than function pointers. Unless there are specific performance concerns, it's generally recommended to use std::function for passing around callbacks.
When to Use Function Pointers:
If performance is a critical consideration and the callback function does not need to capture any context variables, then a function pointer may be a better option. However, this scenario is relatively rare.
Third Option: Template Parameter
Consider using a template parameter if you want the callback function to be any callable object. This approach provides flexibility but requires the outer function to be implemented in the header.
Summary Table:
Feature | Function Pointer | std::function | Template Parameter |
---|---|---|---|
Can capture context | No | Yes | Yes |
Call overhead | None | Small | None |
Can be inlined | No | No | Yes |
Can be stored in class member | Yes | Yes | No |
Implemented outside of header | Yes | Yes | No |
Supported without C 11 standard | Yes | No | Yes |
Readability | Poor | Good | Fair |
Conclusion:
In general, the advantages of std::function outweigh those of function pointers. It's more flexible, future-proof, and readable. Use function pointers only if there's a specific performance concern or if the callback function does not need to capture any context variables.
The above is the detailed content of std::function vs. Function Pointers: When Should You Choose What?. For more information, please follow other related articles on the PHP Chinese website!