When doing Function Pointers what is the purpose of using the address-of operator vs not using it?

后端 未结 4 1501
别那么骄傲
别那么骄傲 2021-01-12 06:17

For the following code snippets why would I use one assignment vs another? thx

void  addOne(int &x)
{
    x +=1;
}

void (*inc)(int &x) = addOne;           


        
相关标签:
4条回答
  • 2021-01-12 06:28

    A function is already a pointer; therefore, you do not need the address operator.

    0 讨论(0)
  • 2021-01-12 06:34

    Brevity, style. It's the same with using * when calling them.

    Also note array vs &array[0].

    0 讨论(0)
  • 2021-01-12 06:39

    From the book C++ Programming Languauge, it is cleary indicated that & and * operators are optional for pointers to functions:

    There are only two things one can do to a function: call it and take its address. The pointer obtained by taking the address of a function can then be used to call the function. For example:

    void error (string s) { /* ... */ }
    void (*efct )(string ); // pointer to function
    void f ()
    {
      efct = &error ; // efct points to error
      efct ("error "); // call error through efct
    }
    

    The compiler will discover that efct is a pointer and call the function pointed to. That is, dereferencing of a pointer to function using * is optional. Similarly, using & to get the address of a function is optional:

    void (*f1 )(string ) = &error ; // ok
    void (*f2 )(string ) = error ; // also ok; same meaning as &error
    void g ()
    {
      f1 ("Vasa"); // ok
      (*f1 )("Mary Rose"); // also ok
    }
    

    As others pointed out, pointer to member function is new/different in C++. The & is not optional to point a member and it is explained as (in C++ Programming Languauge Book):

    A pointer to member can be obtained by applying the address-of operator & to a fully qualified class member name, for example, &Std_interface::suspend.

    0 讨论(0)
  • 2021-01-12 06:42

    The purpose of one over the other is C compatibility. C said that functions will decay to pointers-to-functions automatically. To be compatible, C++ had to do the same.

    Note that when C++ introduced a new function pointer type (member function pointers), they do not decay automatically. So if the C++ committee had their way, odds are good you'd need that & there.

    0 讨论(0)
提交回复
热议问题