从指向具有相同签名的函数的指针转换为函数指针,但参数的附加限定除外
converting to function pointer from pointer to function with same signature, except additional qualification of parameter
void ( * pFunc_pcInt ) ( int const * ) = nullptr ;
void ( * pFunc_pInt ) ( int * ) = reinterpret_cast< void ( * ) ( int * ) >( pFunc_pcInt ) ;
这样的转换会导致未定义的行为吗?
从 standard
(工作草案,强调我的):
A function pointer can be explicitly converted to a function pointer of a different type. [ Note: The effect of calling a function through a pointer to a function type ([dcl.fct]) that is not the same as the type used in the definition of the function is undefined. — end note ] [...]
当然,void(int const *)
和 void(int *)
是不同的类型。
类似的东西来自最著名的online reference(强调我的)之一:
Any pointer to function can be converted to a pointer to a different function type. Calling the function through a pointer to a different function type is undefined, but converting such pointer back to pointer to the original function type yields the pointer to the original function.
在您的特定情况下,这无关紧要,因为您正在将 nullptr
分配给函数指针。在任何情况下调用它都会导致错误。
话虽这么说,如果您已将有效函数指针分配给 pFunc_pcInt
,通过转换后的指针 pFunc_pInt
调用它将会是一个 UB。
void ( * pFunc_pcInt ) ( int const * ) = nullptr ;
void ( * pFunc_pInt ) ( int * ) = reinterpret_cast< void ( * ) ( int * ) >( pFunc_pcInt ) ;
这样的转换会导致未定义的行为吗?
从 standard (工作草案,强调我的):
A function pointer can be explicitly converted to a function pointer of a different type. [ Note: The effect of calling a function through a pointer to a function type ([dcl.fct]) that is not the same as the type used in the definition of the function is undefined. — end note ] [...]
当然,void(int const *)
和 void(int *)
是不同的类型。
类似的东西来自最著名的online reference(强调我的)之一:
Any pointer to function can be converted to a pointer to a different function type. Calling the function through a pointer to a different function type is undefined, but converting such pointer back to pointer to the original function type yields the pointer to the original function.
在您的特定情况下,这无关紧要,因为您正在将 nullptr
分配给函数指针。在任何情况下调用它都会导致错误。
话虽这么说,如果您已将有效函数指针分配给 pFunc_pcInt
,通过转换后的指针 pFunc_pInt
调用它将会是一个 UB。