通过reinterpret_casting方法指针从指针调用派生类的方法。这是 UB 吗?

Calling derived class's methods from pointer to base class via reinterpret_casting the method pointer. Is this UB?

本文关键字:指针 方法 这是 UB 调用 reinterpret casting 通过 派生      更新时间:2023-10-16

通过指向派生类型的对象的指针分配给其基类的指针,我发现您可以将派生类的方法reinterpet_cast到基类的指针,即使基类没有任何此类函数(虚拟、隐藏或其他(。它可以从那里取消引用和调用,它"只是工作"。但我想确保它不是 UB。这是 UB 吗?它是便携式的吗?

可编译示例:

#include <cstdio>
struct A { /* no foo method */ };
struct B : public A { void foo(void){printf("foo");} };
typedef void (B::*B_FOO_PTR)( void );
typedef void (A::*A_FOO_PTR)( void );
int main ( void ) {
    B b;
    A* a = &b;
    // address of a and b are identical
    B_FOO_PTR b_ptr = &B::foo;
    // (a->*b_ptr)(); // COMPILE ERROR: calling B method from A. Not Allowed, but...
    A_FOO_PTR a_ptr = reinterpret_cast<A_FOO_PTR>(b_ptr);
    (a->*a_ptr)(); // works, outputs "foo"
    return 0;
}

这是未定义的行为。唯一可以调用结果的指向成员函数的转换是:

  • 往返转换,以及
  • 指向基数成员的指针到派生成员的指针。

您尝试与第二点相反,该点已从此列表中排除。