In the code below, function-pointer and what i considered as "function-reference" seems to have identical semantics:
#include <iostream> using std::cout; void func(int a) { cout << "Hello" << a << '\n'; } void func2(int a) { cout << "Hi" << a << '\n'; } int main() { void (& f_ref)(int) = func; void (* f_ptr)(int) = func; // what i expected to be, and is, correct: f_ref(1); (*f_ptr)(2); // what i expected to be, and is not, wrong: (*f_ref)(4); // i even added more stars here like (****f_ref)(4) f_ptr(3); // everything just works! // all 4 statements above works just fine // the only difference i found, as one would expect: // f_ref = func2; // ERROR: read-only reference f_ptr = func2; // works fine! f_ptr(5); return 0; }
I used gcc version 4.7.2 in Fedora/Linux
UPDATE
My questions are:
f_ptr = &func;
works? Since func should be decayed into a pointer?f_ptr = &&func;
doesn't work (implicit conversion from void *
)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 by pass by reference.
They're synonymous - "a function pointer" and "a pointer to a function" describe an object that can hold the address of a function.
A pointer is a variable that holds a memory address. A reference has the same memory address as the item it references. A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly.
It's much faster and memory-efficient to copy a pointer than to copy many of the things a pointer is likely to point to. A reference is stored in as many bytes as required to hold an address on the computer. This often makes reference much smaller than the things they refer to.
Functions and function references (i.e. id-expressions of those types) decay into function pointers almost immediately, so the expressions func
and f_ref
actually become function pointers in your case. You can also call (***func)(5)
and (******f_ref)(6)
if you like.
It may be preferable to use function references in cases where you want the &
-operator to work as though it had been applied to the function itself, e.g. &func
is the same as &f_ref
, but &f_ptr
is something else.
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