search

Home  >  Q&A  >  body text

c++ - 内存模型虚函数static变量相关问题

32位机器,sizeof(cTest)=?

class CTest
{
    public:
        CTest():m_chData(‘\0’),m_nData(0)
        {
        }
        virtual void mem_fun(){}
    private:
        char m_chData;
        int m_nData;
        static char s_chData;
};

我的分析如下:
由于有虚函数,所以虚函数指针占4个字节,然后char占一个字节,按4字节对齐,补三位,int 占4个字节 最后static占4个字节。可是运行结果却不是16。
这是什么原因呢?

我在电脑上试图打出CTest类里每个对象的地址,s_chData的地址如何查看呢?
我的代码如下:

int main()
{
    CTest example;
    cout<<&example<<endl;
    cout<<&(example.m_chData)<<endl;
    cout<<&(example.m_nData)<<endl;
    
    return 0;
}
输出结果

0x7fff5fbff7a8

0x7fff5fbff7b4
中间有一个空行,然后试图输出s_chData的地址时提示错误。
黄舟黄舟2882 days ago580

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 13:06:02

    In a class, if there is nothing, the class occupies 1 byte. Once there are other space-occupying members in the class, this 1 byte is not included in the calculation. If a class has only one int, it occupies 4 bytes instead of 5 bytes.
    If there are only member functions, it still only occupies 1 byte, because class functions do not occupy space. Virtual functions require 4 bytes because there is a virtual function table. If the data member object is a pointer, it takes 4 bytes. Note that there is byte alignment. If it is 13 bytes, it will be carried to 16 bytes of space.

    class Empty
    {
    };
    
    sieof(Empty)=1
    如果是
    class Empty
    {
        public:
        virtual foo();
    };
    sizeof(Empty)=指针大小

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 13:06:02

    static needs to be initialized outside the class, the static variable is in the static storage area, and the class object is allocated in the stack space

    reply
    0
  • Cancelreply