The purpose of references to functions

I

Irfy

Could someone elaborate on the purpose and concrete usage scenarios of
references to functions. What can references to functions do that
pointers to functions cannot. Why are they in C++?

A swap function with two reference parameters of the same type is a
typical example to explain the purpose of references to objects in C++
and the way they can be used, but since functions cannot be
"changed" (in the sense "exchange the bodies of functions foo and
bar"), I cannot think of an example making the purpose of references
to functions obvious. I guess I must be missing something.

I found a comment by Rob Williscroft in the Thread
http://groups.google.com/group/comp...st&q=references+to+functions#6c736d2133cf30dc
saying:
Yes, but you could also ask another question, why are references to
functions part of C++ since they don't provide any utility that
isn't provided by function pointers. I think the answer is that
it allows a simple function to behave like a 'functor', particularly
a 'reference to a functor', more efficiently. This is important for
the standard library algorithms.

but I cannot not "see through" this exaplanation, why would a
reference to a function be more efficient, is this just a speculation?

-- Irfy
 
V

Vidar Hasfjord

I found a comment by Rob Williscroft in the Threadhttp://groups.google.com/group/comp.lang.c++/browse_thread/thread/9be...
saying:


but I cannot not "see through" this exaplanation, why would a
reference to a function be more efficient, is this just a speculation?

Conceivably the compiler can have a simpler time optimizing references
because they can never be reassigned; while pointers of course can.
This may allow a call via a reference to a function to be implemented
as a direct function call, maybe even inlined, where a call through a
pointer may end up as an indirect call in the generated code.

Regards,
Vidar Hasfjord
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top