通过reinterpret_casting方法指针,将派生类的方法从指针调用到基类.这是UB吗? [英] Calling derived class's methods from pointer to base class via reinterpret_casting the method pointer. Is this UB?

查看:88
本文介绍了通过reinterpret_casting方法指针,将派生类的方法从指针调用到基类.这是UB吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过将指向派生类型的对象的指针分配给其基类的指针,我发现即使基类没有将方法从派生类重播到基类的指针,没有任何此类功能(虚拟,隐藏或其他功能).可以从那里取消引用和调用它,并且正常工作".但我想确保它不是UB.这是UB吗?便携吗?

With a pointer to an object of a derived type assigned to a pointer of its base class, I've found that you can reinterpet_cast a method from the derived class to a pointer of the base class, even if the base class doesn't have any such function (virtual, hidden, or otherwise). And it can be dereferenced and called from there and it "just works". But I'd like to make sure it's not UB. Is this UB? Is it portable?

可编译示例:

#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;
}

推荐答案

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

This is undefined behaviour. The only pointer-to-member function conversions where you can call the result are:

  • 往返转换,和
  • 指向成员的基础指针.

您尝试第二点的倒数,该点不包括在此列表中.

You attempt the inverse of the second point, which is excluded from this list.

这篇关于通过reinterpret_casting方法指针,将派生类的方法从指针调用到基类.这是UB吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆