reinterpret_cast到函数指针

St.*_*rio 5 c++ reinterpret-cast

我已经为实验编写了代码 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?
}
Run Code Online (Sandbox Code Playgroud)

首先,为什么reinterpret_cast允许这种转换?我认为这种转换是不正确的。

ahr*_*uss 6

标准(C++11 §5.2.10/6) 说

指向函数的指针可以显式转换为指向不同类型函数的指针。通过指向与函数定义中使用的类型不同的函数类型的指针调用函数的效果是未定义的。除了将“指向 T1 的指针”类型的纯右值转换为“指向 T2 的指针”类型(其中 T1 和 T2 是函数类型)并返回其原始类型会产生原始指针值之外,这种指针转换的结果是未指定的.

所以这是未定义的行为。

  • @St.Antario:这是真的。但是,函数类型 *decays* 几乎在所有上下文中都变成了函数指针类型。这种情况与数组发生的情况非常相似。阻止函数类型 *decay* 的唯一上下文是一元 `&amp;` 运算符、`sizeof` 运算符和其他一些。`reinterpret_cast` 也不例外,这意味着每次将函数名指定为操作数时,它都会隐式转换为函数指针类型。即`reinterpret_cast&lt;&gt;(foo)` 完全等同于`reinterpret_cast&lt;&gt;(&amp;foo)`。 (3认同)
  • @St.Antario 来自 §4.3/1:“函数类型 T 的左值可以转换为“指向 T 的指针”类型的右值。结果是一个指向函数的指针。” (3认同)
  • 怎么不清楚?“指向函数 ** 的指针可以显式转换**为指向不同类型函数的指针。” (2认同)