I'm using function pointers a lot in my c++
code, always in a way conforming to this simple canonical example (e.g. the functions have the same I/O, but the desired operation is only known at run time):
#include <iostream>
using namespace std;
int add(int first, int second){
return first + second;
}
int subtract(int first, int second){
return first - second;
}
int operation(int first, int second, int (*functocall)(int, int)){
return (*functocall)(first, second);
}
int main(){
int a, b;
int (*plus)(int, int) = add;
int (*minus)(int, int) = subtract;
a = operation(7, 5, plus);
b = operation(20, a, minus);
cout << "a = " << a << " and b = " << b << endl;
return 0;
}
I started using this a while ago simply because I found it simpler to use.
As I learn c++ better, I find myself wondering: is this construct, in this context, bad from a performance point of view? If so why and what is the better c++11
-ish alternatives?
I couldn't find precise guidelines for this simple usage case, from a performance point of view (though plenty of guidelines for more complicated cases)
Im implicitly assuming run of the mill x86 hardware.
If you are really worried about performance, you should consider doing compile-time dispatch - templatize operation; This will certainly work for your simple example; not sure if your real use needs true run-time operation binding (in which case this solution doesn't work).
template <typename Functor>
int operation(int first, int second, Functor f)
{
return f(first, second);
}
...
a = operation(7, 5, std::plus<int> /* since C++14, roll your own otherwise */);
b = operation(20, a, std::minus<int>);
The performance overhead of calling through function pointers is certainly not negligible, especially for functions as short as add() and subtract(); That's the reason why the C++ std::sort beats the pants off of C's qsort routine for simple basic types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With