问题
Here, in this code, the size of ob1 is 16 which is fine(because of the virtual pointer) but I can't understand why the size of ob2 is 24.
#include <iostream>
using namespace std;
class A {
int x;
};
class B {
int y, z;
};
class C : virtual public A {
int a;
};
class D : virtual public B {
int b;
};
int main() {
C ob1;
D ob2;
cout << sizeof(ob1) << sizeof(ob2) << "\n";
}
I expect the size of ob2 as 20, but the output is 24
回答1:
One possible layout for objects of type D
is:
+----------+
| y | The B subobject (8 bytes)
| z |
+----------+
| vptr | vtable pointer (8 bytes)
| |
+----------+
| b | 4 bytes
+----------+
| unused | 4 bytes (padding for alignment purposes)
+----------+
That would make sizeof(ob2)
24.
Alignment requirements are defined by an implementation. Most of the time, the size of the largest member object or subobject dictates the alignment requirement of an object. In your case, the size of the largest object, the vtable pointer, is 8 bytes. Hence, the implementation aligns objects at 8 bit boundaries, adding padding when necessary.
回答2:
To implement the virtual inheritance, D
contains as data member a pointer, which on a 64 bit system requires 8 bytes. Moreover, these 8 bytes must be aligned to a 8-byte memory boundary. This latter requirement in turn mandates that D
itself be aligned to a 8-byte memory boundary. The simplest way to implement that is to make sizeof(D)
a multiple of 8 by padding it with unused bytes (21-24).
来源:https://stackoverflow.com/questions/57481249/virtual-class-inheritance-object-size-issue