处理多重继承时如何对齐指针?

mis*_*why 0 c++ pointers multiple-inheritance memory-alignment vtable

假设我们有一个具体的类A和一个抽象类B.

考虑一个具体的C,它继承自A和B,并实现B:

class C : public A, public B  
{  
/* implementation of B and specific stuff that belongs to C */  
};
Run Code Online (Sandbox Code Playgroud)

现在我定义一个签名是什么的函数 void foo(B* b);

这是我的代码,我可以假设每个指向B的指针都是A和B.在foo的定义中,如何获得指向A的指针?一个讨厌但有效的技巧是将指针对齐,如下所示:

void foo(B* b)  
{  
    A* a = reinterpret_cast<A*>(reinterpret_cast<char*>(b) - sizeof(A));
    // now I can use all the stuff from A  
}
Run Code Online (Sandbox Code Playgroud)

请记住,C没有超类型,实际上,有许多类似于C的类,只有A和B.可以自由地质疑我的逻辑和这个设计样本,但问题只是关于指针对齐.

Jur*_*lie 6

void foo(B* b)  
{  
    //A* a = reinterpret_cast<A*>(reinterpret_cast<char*>(b) - sizeof(A)); // undefined behaviour!!!!
    A* a = dynamic_cast<A*>(b);
    if (a)
    {
       // now I can use all the stuff from A  
    }
    else
    {
       // that was something else, not descended from A
    }
}
Run Code Online (Sandbox Code Playgroud)

忘了说:为了使工作动态转换,A和B应该具有虚函数或至少虚拟析构函数.否则,没有合法的方法来进行类型转换.

  • -1:这不起作用.它甚至不会编译. (2认同)