次のコードフラグメントの場合。
/*This program demonstartes how a virtual table pointer
* adds to a size of a class*/
class A{
};
class X{
public:
void doNothing(){}
private:
char a;
};
class Z:public X {
public:
void doNothing(){}
private:
char z;
};
class Y{
public:
virtual void doNothing(){}
private:
char a;
};
class P:public Y {
public:
void doNothing(){}
private:
char pp[4];
};
int main(){
A a;
X x;
Y y;
Z z;
P p;
std::cout << "Size of A:" << sizeof(a) << std::endl;// Prints out 1
std::cout << "Size of X:" << sizeof(x) << std::endl;//Prints out 1
std::cout << "Size of Y:" << sizeof(y) << std::endl;//Prints 8
std::cout << "Size of Z:" << sizeof(z) << std::endl;
//Prints 8 or 12 depending upon wether 4 bytes worth of storrage is used by Z data member.
std::cout << "Size of P:" << sizeof(p) << std::endl;
std::cout << "Size of int:" << sizeof(int) << std::endl;
std::cout << "Size of int*:" << sizeof(int*) << std::endl;
std::cout << "Size of long*:" << sizeof(long*) << std::endl;
std::cout << "Size of long:" << sizeof(long) << std::endl;
return 0;
}
私が気付いたように見える動作は、空のクラスがインスタンス化されるか、空のクラスがバイト境界から継承されるときはいつでも考慮されない(つまり、サイズ1バイトのオブジェクトが許可される)場合、他のすべての場合、オブジェクトサイズは次のように決定されるようです。バイト境界。
これの理由は何ですか?この時点で私は推測しているので、私は尋ねます。