c++ - 从指向具有相同签名的函数的指针转换为函数指针,但参数的附加限定除外

标签 c++ function-pointers undefined-behavior reinterpret-cast

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/

相关文章:

c++ - 编写函数指针比调用函数指针好在哪里?

c++ - int 和 double 的均匀随机分布 "base class"?

c++ - 在C/C++中检测签名溢出

在 QVector 中使用指针和非指针参数的 C++ 模板

c++ - 关于按属性配对用户的问题..算法/数据结构

function - 在没有 if-else/switch-case 语句的情况下控制程序流

c - 为什么 printf ("%d",1/0.0) 的输出是 0?

c++ - 当基类的 POD 成员不打算由它初始化时,在调用其构造函数之前初始化它是否合法?

c++ - 程序应何时通知用户它无法打开文件?

c++ - 使用 C++11 可变参数模板包装 Loki::Typelist