c – 继承自具有虚函数的基类的类的sizeof

对于以下代码片段.

/*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字节的对象),在其他每种情况下,对象大小似乎由字节边界.

这是什么原因?我问,因为在这一点上我猜.

最佳答案
这是Stroustrup的explanation,为什么空类的大小不能为零.至于为什么它是1个字节,而不是符合对齐边界的东西,我猜这取决于编译器.

转载注明原文:c – 继承自具有虚函数的基类的类的sizeof - 代码日志