转换后函数指针地址是否保留?

sky*_*ack 6 c++ function-pointers language-lawyer reinterpret-cast

据我了解,C++ 标准允许将函数指针转换为不同类型(只要从不调用它们):

int my_func(int v) { return v; }

int main() {
    using from_type = int(int);
    using to_type = void(void);

    from_type *from = &my_func;
    to_type *to = reinterpret_cast<to_type *>(from);

    // ...
}
Run Code Online (Sandbox Code Playgroud)

此外,如果我将指针强制转换回其原始类型并调用它,则不会出现未定义的行为。

到目前为止,一切都很好。那么下面的呢?

const bool eq = (to == reinterpret_cast<to_type *>(my_func));
Run Code Online (Sandbox Code Playgroud)

转换后地址是否也保持不变,或者标准不保证这一点?


虽然这与问题无关,但一种可能的情况是当人们努力进行类型擦除时。如果地址成立,则无需知道原始函数类型即可完成某些操作。

dav*_*ave 5

来自[expr.reinterpret.cast].6(强调我的):

\n
\n

函数指针可以显式转换为不同类型的函数指针。\n[...]

\n

除了将 \xe2\x80\x9c 类型的指针到 T1\xe2\x80\x9d 的纯右值转换为\n\xe2\x80\x9c 类型的指针到 T2\xe2\x80\x9d (其中 T1 和 T2 是函数类型)以及返回到其原始类型会产生原始指针值,这种指针转换的结果是未指定的。

\n
\n

因此,该标准明确允许将函数指针转换为不同的 FP 类型,然后再转换回来。这是未指定reinterpret_cast函数指针这一一般规则的一个例外。

\n

根据我的理解,这意味着to == reinterpret_cast<to_type *>(my_func)不一定是true

\n