【问题标题】:Why is static_cast from int (*)(int) to void* not allowed in C++?为什么在 C++ 中不允许从 int (*)(int) 到 void* 的 static_cast?
【发布时间】:2020-06-24 23:42:08
【问题描述】:

请考虑以下代码:

int f(int i){return i*i;};

int main() {

    void* p = static_cast<void*>(&f);

    return 0;
}

您可以see here 代码无法编译。 为什么 C++ 中不允许 static_castint (*)(int)void*

【问题讨论】:

标签: c++ casting void-pointers


【解决方案1】:

您不能使用static_cast 将函数指针强制转换为void*,但您可以使用reinterpret_cast 来执行此操作。

这是条件支持,具有实现定义语义,除了转换回原始函数指针类型会产生相同的指针值,因此可以使用它再次调用该函数。

可能不允许您对以这种方式获得的void* 执行任何其他操作,但您需要查看编译器文档以确定这一点。 (编译器应该记录实现定义的行为,但通常做得不好或根本没有。)

特别是在 POSIX 系统和 Windows 上,始终支持此转换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    相关资源
    最近更新 更多