c++ - 在 C 和 C++ 中的函数指针和对象指针之间转换

标签 c++ c

我对以下内容有误吗?

C++ 标准规定指针到函数和指针到对象(以及返回)之间的转换是由实现定义的语义条件支持的,而所有 C 标准都说这在所有情况下都是非法的,对吧?

void foo() {}

int main(void)
{
    void (*fp)() = foo;
    void* ptr = (void*)fp;
    return 0;
}

ISO/IEC 14882:2011

5.2.10 重新解释类型转换 [expr.reinterpret.cast]

8 Converting a function pointer to an object pointer type or vice versa is conditionally-supported. The meaning of such a conversion is implementation-defined, except that if an implementation supports conversions in both directions, converting a prvalue of one type to the other type and back, possibly with different cvqualification, shall yield the original pointer value.

我现在在 C 标准中找不到任何关于它的内容...

最佳答案

  • 在 C++03 中,此类转换是非法的(不是 UB)。编译器应该发出诊断。 Unix 系统上的许多编译器都没有发出诊断。这本质上是标准、POSIX 与 C++ 之间的冲突。
  • 在 C++11 中,“有条件地支持”此类转换。如果系统确实支持这种转换,则不需要诊断;没有什么可诊断的。
  • 在 C 中,这种转换正式是未定义的行为,因此不需要诊断。如果系统碰巧做了“正确”的事情,那么这就是实现 UB 的一种方式。
  • 在 C99 中,这又是 UB。但是,该标准还将此类转换列为该语言的“通用扩展”之一:

    J.5.7 Function pointer casts
    A pointer to an object or to void may be cast to a pointer to a function, allowing data to be invoked as a function (6.5.4).
    A pointer to a function may be cast to a pointer to an object or to void, allowing a function to be inspected or modified (for example, by a debugger) (6.5.4).

关于c++ - 在 C 和 C++ 中的函数指针和对象指针之间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14125474/

相关文章:

c - 用于基于 XA/SmartXA/SmartXA2 的 Controller 的免费 C 编译器。有吗?

比较两个内存块之间的值是否相等

c - 使用 typedef 和结构时出错

c++ - 非限定或指针/引用类型的特征

c++ - 缓动函数的持续时间是多少

c++ - OpenCV 从 C++ 到 C 的转换

c - 执行C程序时出现碎片错误

c - 使用 MPI_Scatter 发送矩阵的列

c++ - 如何将菜单栏添加到我的 WTL 对话窗口?

c++ - 我可以通过模板 C++ 将对象传递给类吗