[英]Do function pointer addresses hold after conversions?
据我了解,C++ 标准允许将 function 指针转换为不同的类型(只要从不调用它们):
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);
// ...
}
此外,如果我将指针转换回其原始类型并调用它,则没有未定义的行为。
到目前为止,一切都很好。 那么接下来呢?
const bool eq = (to == reinterpret_cast<to_type *>(my_func));
转换后地址是否也保留,或者标准不保证这一点?
虽然这与问题无关,但一种可能的情况是当一个人在类型擦除上努力时。 如果地址成立,则无需知道原始 function 类型即可完成某些操作。
来自[expr.reinterpret.cast].6 (强调我的):
function 指针可以显式转换为不同类型的 function 指针。 [...]
除了将“指向 T1 的指针”类型的纯右值转换为“指向 T2 的指针”类型(其中 T1 和 T2 是 function 类型)并返回其原始类型产生原始指针值外,这种指针转换的结果是未指定的.
因此,该标准明确允许将 function 指针转换为不同的 FP 类型,然后返回。 这是未指定reinterpret_cast
ing function 指针的一般规则的例外。
在我的理解中,这意味着to == reinterpret_cast<to_type *>(my_func)
不一定是true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.