gpt4 book ai didi

c++ - 将成员函数指针强制转换为另一个类并再次返回是否安全?

转载 作者:行者123 更新时间:2023-11-30 01:11:26 25 4
gpt4 key购买 nike

阅读这个问题的答案 ( Casting a function pointer to another type ),我明白将像 void(*)(A*) 这样的指针转换为像 void(*) 这样的指针是安全的(B*),你只需要在调用它们之前将它们转换回来。

这是否也适用于成员函数指针?我可以安全地将 void(A::*)() 转换为 void(B::*)() 并在调用它之前将其转换回来吗?

至少在我的系统上似乎有效的示例代码:

#include <iostream>

struct A {
void f() { std::cout << "called" << std::endl; }
};

struct B {};

int main() {
A instance;
auto ptr = reinterpret_cast<void (B::*)()>(&A::f);
(instance.*(reinterpret_cast<void (A::*)()>(ptr)))();
}

最佳答案

从 5.2.10/10 (reinterpret_cast) 我们了解到:

A prvalue of type “pointer to member of X of type T1” can be explicitly converted to a prvalue of a different type “pointer to member of Y of type T2” if T1 and T2 are both function types or both object types.71 The null member pointer value (4.11) is converted to the null member pointer value of the destination type. The result of this conversion is unspecified, except in the following cases:

  • converting a prvalue of type “pointer to member function” to a different pointer to member function type and back to its original type yields the original pointer to member value.

在这种情况下,您正在转换到指向成​​员函数的指针和从指向成员函数的指针(都指向函数),所以它看起来完全合法。

关于c++ - 将成员函数指针强制转换为另一个类并再次返回是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36158598/

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