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

StackOverflow https://stackoverflow.com/questions/22396799

  •  14-06-2023
  •  | 
  •  

Вопрос

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?

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top