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

标签 c++ pointers multiple-inheritance vtable memory-alignment

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

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

class C : public A, public B  
{  
/* implementation of B and specific stuff that belongs to C */  
};

现在我定义了一个函数,它的签名是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  
}

请记住,C 没有父类(super class)型,实际上,有许多类似于 C 的类,它们只有 A 和 B。请随意质疑我的逻辑和这个设计示例,但问题只是关于指针对齐。

最佳答案

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

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

关于c++ - 处理多重继承时如何对齐指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5673694/

相关文章:

database - Entity Framework : Multiple Inheritance

c++ - 动态链接库 - 构建可执行文件时成功,创建另一个 .so 时相同的设置失败

c++ - boost multi_index - 如何让它按插入排序?

c++ - 一切都不稳定

c++ - 使用 Ackermann 函数 C++ 进行内存

pointers - MIPS 汇编指针到指针?

c++ - 内存删除的运行时检测

c++ - 如何修复未对齐的指针 (char**)

Python 3.x : Avoid overwriting of same methods from different inherited classes

ruby - ruby 可以实现多重继承吗?