gpt4 book ai didi

c++ - 重新解释为函数指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:21 26 4
gpt4 key购买 nike

这是我为 reinterpret_cast<T> 实验编写的代码

#include <iostream>
#include <cstdlib>

using std::cout;
using std::endl;

int foo()
{
cout << "foo" << endl;
return 0;
}

void (*bar)();
int main()
{

bar = reinterpret_cast<void (*)()>(foo); //Convertion a function type to a pointer to function type
bar(); //displays foo. Is it UB?
}

首先为什么这样reinterpret_cast允许转换?我认为这种转换是错误的。

最佳答案

The standard (C++11 §5.2.10/6) 说

A pointer to a function can be explicitly converted to a pointer to a function of a different type. The effect of calling a function through a pointer to a function type that is not the same as the type used in the definition of the function is undefined. Except that converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.

所以这是未定义的行为。

关于c++ - 重新解释为函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25131019/

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