3

Consider the code:

void f(int) {}

int main()
{
    std::function<void(int)>func = f;
    func(3);
    std::function<void(int)>funcc = &f;
    funcc(3);

    void(*ptr)(int) = f;
    ptr(3);
    void(*ptrr)(int) = &f;
    ptrr(3);
}

This code compiles successfully and it seems to me like all the calls of f are the same. In the first part function is being made a functor with wrapping in std::function and in the second part I'm using pointers to function.

My main question is: what is the difference between writing = f; and = &f;? Moreover, what is &f? Is it an address of f? Or a reference to f? I'll highly appreciate any explanations!

Aleksandr Tukallo
  • 1,299
  • 17
  • 22
  • 1
    In many cases, just using the name of the function decays into a function pointer. For instance http://stackoverflow.com/q/26559758/1171191 – BoBTFish Dec 25 '16 at 09:27
  • you also can write (*ptr)(3), (**ptr)(3), etc. (), always operates on a pointer-to-function. When you write (*p)(), the pointer is dereferenced, and then immediately un-dereferenced again so that the function call operator gets what it wants. Same with f and &f, it gets dereferenced to pointer to function. – Swift - Friday Pie Dec 25 '16 at 09:39
  • 2
    There's no difference, there is implicit conversion from function to pointer-to-function – M.M Dec 25 '16 at 09:41

0 Answers0