Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantages of passing around functions?

I'm learning C++ (coming from java) and recently discovered that you can pass functions around. This is really cool and I think immensely useful. Now I was thinking on how I could use this and one of the idea's that popped into my head was a completely customizable class.

The best example of my train of though for completely customizable classes (code) would be say a person class. Person would have all functions pertaining to P. Later Person may pick up a sword (S), so now Person has access to all functions pertaining to both P and S.

Are there limits or performance issues with this? Is this sloppy and just plain frowned upon?

Any insight is educational, thanks.

~Aedon

like image 286
ahodder Avatar asked May 10 '11 20:05

ahodder


1 Answers

When passing around functions - i.e. pointers to functions really - calls are always indirect and therefore possibly slower than a direct call (and definitely slower than an inlined call altogether).

The STL is modeled with functors. That is: light function objects that have a operator() member which gets called. This has the advantage of being a very likely candidate for inlining, especially if the functor and operator() are very simple (as e.g. std::less<T>).

See also: http://www.sgi.com/tech/stl/functors.html

like image 87
Marcus Borkenhagen Avatar answered Sep 20 '22 02:09

Marcus Borkenhagen