简体   繁体   中英

Do function pointer addresses hold after conversions?

From what I understand, casting function pointers to different types is allowed by the C++ standard (as long as one never invokes them):

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);

    // ...
}

Moreover, there is no undefined behavior if I cast the pointer back to its original type and invoke it.

So far, so good. What about the following, then?

const bool eq = (to == reinterpret_cast<to_type *>(my_func));

Does the address hold, too, after the conversion, or is this not guaranteed by the standard?


While this is irrelevant to the question, a possible scenario is when one goes hard on type erasure. If the address holds, something can be done without having to know the original function type.

From [expr.reinterpret.cast].6 (emphasis mine):

A function pointer can be explicitly converted to a function pointer of a different type. [...]

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.

So, the standard explicitly allows casting function pointers to different FP types and then back. This is an exception to the general rule that reinterpret_cast ing function pointers is unspecified .

In my understanding, that means to == reinterpret_cast<to_type *>(my_func) need not necessarily be true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM