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。
关于c++ - 从指向具有相同签名的函数的指针转换为函数指针,但参数的附加限定除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42212372/