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?
Use references when you can, and pointers when you have to. References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced but pass by reference.
The difference between pass-by-reference and pass-by-pointer is that pointers can be NULL or reassigned whereas references cannot. Use pass-by-pointer if NULL is a valid parameter value or if you want to reassign the pointer. Otherwise, use constant or non-constant references to pass arguments.
You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to. This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.
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.
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