Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use function reference instead of function pointer in C++? [duplicate]

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?

like image 844
songyuanyao Avatar asked Mar 14 '14 05:03

songyuanyao


People also ask

When should I use references and when should I use pointers?

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.

Why are references better than pointers?

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.

Which is better pass by reference or pass by pointer?

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.

Should pointers be passed by reference?

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.


1 Answers

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.

like image 162
Vaibhav Jain Avatar answered Sep 29 '22 08:09

Vaibhav Jain