【问题标题】:Calling derived class's methods from pointer to base class via reinterpret_casting the method pointer. Is this UB?通过方法指针中的 reinterpret_cast 从指向基类的指针调用派生类方法。这是UB吗?
【发布时间】:2019-11-18 11:28:18
【问题描述】:

通过将指向派生类型对象的指针分配给其基类的指针,我发现您可以将派生类中的方法重新转换为基类的指针,即使基类没有' 没有任何此类功能(虚拟、隐藏或其他)。它可以被取消引用并从那里调用,它“正常工作”。但我想确保它不是 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;
}

【问题讨论】:

  • 是的,这是未定义的行为。

标签: c++ inheritance reinterpret-cast member-pointers


【解决方案1】:

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

  • 往返转换,以及
  • pointer-to-member-of-base 指向pointer-to-member-of-derived。

您尝试第二点的倒数,该点已从该列表中排除。

【讨论】:

  • 第二点,您需要使用标准转换(例如,根本不使用“cast”或通过static_cast),而不是reinterpret_cast
猜你喜欢
  • 2019-11-18
  • 1970-01-01
  • 2014-02-15
  • 2016-07-03
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
相关资源
最近更新 更多