My rule of thumb is:
Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.
Use references otherwise.
For the language difference (keeping only the function declarations below, since that's what's important only)
void execute( void (&func)() );
void g();
int main() {
void (*fp)() = g;
execute(fp); // doesn't work
execute(&g); // doesn't work either
execute(g); // works
}
It doesn't work, because it wants a function, not a function pointer. For the same reason that array answer rejects a pointer, this rejects a pointer too. You have to pass "g" directly.
For templates, it matters too
template<typename T>
void execute(T &t) { T u = t; u(); }
template<typename T>
void execute(T t) { T u = t; u(); }
Those two are very different from one another. If you call it with execute(g);
like above, then the first will try to declare a function and initialize it with t
(reference to g
). The generated function would look like this
void execute(void(&t)()) { void u() = t; u(); }
Now you can initialize references and pointers to functions, but of course not functions itself. In the second definition, T
will be deduced to a function pointer type by template argument deduction, and passing a function will convert it to that pointer parameter type implicitly. So everything will go fine.
I don't know why MSVC treats them differently for inlining - but i also suspect it's because function references appear more seldom.
Best Answer
First, a reference to a pointer is like a reference to any other variable:
A pointer to reference is illegal in C++, because -unlike a pointer- a reference is just a concept that allows the programmer to make aliases of something else. A pointer is a place in memory that has the address of something else, but a reference is NOT.
Now the last point might not be crystal clear, if you insist on dealing with references as pointers. e.g.:
As you can see from the above code, when we use the reference, we are not dealing with something separated from what it refers to. So, the address of a reference is just the address of what it refers to. Thats why there is no such thing called the address of the reference in terms of what you are talking about.