11

When to use function reference such as

void (&fr)() = foo;
fr();

instead of function pointer such as

void (*fp)() = &foo;
fp();

Is there something function pointer can't do but function reference can?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Also, what can be said for non-function pointers and references can also be applied to function pointers and references. There could be some exceptions though. – Mark Garcia Mar 14 '14 at 05:31

1 Answers1

3

when you define a reference:

void (&fr)() = foo;
fr();

it gives you the ability to use fr almost everywhere where it would be possible to use foo, which is the reason why:

fr();
(*fr)();

works exactly the same way as using the foo directly:

foo();
(*foo)();

One more Difference is dereferencing a function reference doesn't result in an error where function pointer does not require dereferencing.

JFMR
  • 23,265
  • 4
  • 52
  • 76
Vaibhav Jain
  • 3,729
  • 3
  • 25
  • 42
  • This answer doesn't actually answer the question asked. Had `fr` been declared as `void (*fr)() = &foo`, it would still be equally possibly to write `fr()`. Both can be written with or without explicit dereferences. Thus you answered a question about what the differences between function references and function pointers are, by pointing out ways they're the same... – underscore_d Oct 23 '21 at 14:41