Cast a function pointer

后端 未结 2 885
孤独总比滥情好
孤独总比滥情好 2020-12-12 00:55

Suppose I have a function

void myFun(int*) 
In C++ what exactly does the following mean


  ( void(*)(void*) )&myFun

2条回答
  •  孤街浪徒
    2020-12-12 01:43

    The cast is permitted, by 5.2.10 (6):

    A function pointer can be explicitly converted to a function pointer of a different type. The effect of calling a function through a pointer to a function type (8.3.5) that is not the same as the type used in the definition of the function is undefined. Except that converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.

    This is equivalent to C 6.3.2.3 (8):

    A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.

    In practice, calling through a function pointer with different but compatible argument types (especially pointer types) usually succeeds, and has the effect of a C-style cast on the arguments. This is by no means guaranteed, however; https://stackoverflow.com/a/189126/567292 discusses a case where gcc decided to make such undefined function pointer cast calls abort.

提交回复
热议问题