gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:10:35 25 4
gpt4 key购买 nike

我对以下内容有误吗?

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com