reinterpret_cast指向 void(*&)() 的成员函数指针
reinterpret_cast member function pointer to void(*&)()
成员函数指针不能reinterpret_cast
到函数指针。(不过,GCC 需要-pedantic-errors
标志来强制执行这一点。
但是,GCC,Clang和MSVC似乎同意将成员函数指针转换为对函数指针的引用是可以的。请参阅以下示例:
#include<type_traits>
struct A {
void f() {}
};
int main() {
auto x = &A::f;
auto y = reinterpret_cast<void(*&)()>(x);
// auto y = reinterpret_cast<void(*)()>(x);
static_assert(std::is_same_v<decltype(y), void(*)()>);
}
戈博尔特在这里
该程序在所有三个编译器上编译,但是当使用注释行而不是前一个时,无法在所有编译器上编译(带有迂腐的标志(。
我在标准中没有看到任何允许这种转换的规则。是程序格式不正确,编译器无法诊断,还是程序格式正确?
如果是后者,确切的转换顺序是什么,标准允许在哪里,函数指针是否可以转换回原始类型以调用它,或者是否使用引用来初始化y
已经未定义的行为?
reinterpret_cast<T&>(x)
等效于*reinterpret_cast<T*>(&x)
。
换句话说,reinterpret_cast<void(*&)()>(x)
对指针本身执行类型双关语。
像往常一样,访问此强制转换的结果会违反严格的别名并导致未定义的行为。
我在标准中没有看到任何允许这种转换的规则。
这里:
[expr.reinterpret.cast]/11:
如果"指向
T1
的指针"类型的表达式可以使用reinterpret_cast
显式转换为"指向T2
的指针"类型,则可以将类型转换为"指向T2
的"类型的T1
的 glvalue,指定一个对象x
。 结果是*reinterpret_cast<T2 *>(p)
的结果,其中p
是指向"指向T1
的指针"类型的x
的指针。...
由于始终允许在指向对象类型的指针之间reinterpret_cast
(在您的情况下,在指向指针(指向 [成员] 函数(的指针之间(,因此在您的情况下也允许这样做。
- 从成员指针到整个结构/类的强制转换
- OOP 中的单成员指针
- 使用结构成员指针在C++中填充结构
- 聚合初始化,将成员指针设置为同一结构成员
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 共享 C++ 的数据成员指针
- 如何声明指向成员内容的成员指针m_pmd/m_pmf并访问它们?
- 从类C++外部调用指向成员方法的成员指针
- 结构成员指针是否自动初始化为零?
- 如何删除类内类类型的类成员指针
- 是否打印指向已定义 int 的成员指针
- 指向常量的成员指针
- 通过此指针访问时的成员差异和自身的成员指针(简单的 QT 示例问题)
- 类数据成员指针的非类型模板参数包无法使用 gcc 编译
- 为什么我不能在同一行中定义两个相同类型的类的成员指针
- 将类成员指针传递给 Lambda 捕获列表 c++11
- 在单一实例类中将成员指针设置为 null 的正确方法是什么
- 无法删除在destructor中的成员指针的课程
- 删除对象而不调用成员指针的析构函数
- 当派生类的基类具有成员指针时,对其进行深层复制