c++ - 通过方法指针中的 reinterpret_cast 从指向基类的指针调用派生类方法。这是UB吗?

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

通过将指向派生类型对象的指针分配给其基类的指针,我发现您可以将派生类的方法重新转换为基类的指针,即使基类没有' 具有任何此类功能(虚拟的、隐藏的或其他)。并且可以从那里取消引用和调用它并且它“正常工作”。但我想确保它不是 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++ - 通过方法指针中的 reinterpret_cast 从指向基类的指针调用派生类方法。这是UB吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56943547/

相关文章:

c++ - 服务器关闭永远不会完成

java - Java 对象的最具体的子类?

java - Java中奇怪的类型不匹配问题

c++ - 如何对内部模板类使用重新解释强制转换?

c++ - 为什么我必须在这里使用dynamic_cast

c++ - std::list<int> 的默认构造函数可以抛出吗?

c++ - __FILE__ 返回路径为 "\/"的字符串

c++ - 根据对的第二个值查找对 vector 的上限

c# - 糟糕设计的空抽象类/接口(interface)标志?

c++ - 有人可以使用 reinterpret_cast 解释这行 c++ 代码吗?