空类、空结构体占多少字节

#include "mainwindow.h"
#include <QApplication>
#include <QtDebug>

struct STR
{
    
    
};

class Test
{
    
    
public:
    Test() {
    
    }
};

int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);
    STR aa,bb;
    Test cc,dd;
    qDebug() << "aa" << sizeof(aa) << &aa;
    qDebug() << "bb" << sizeof(bb) << &bb;
    qDebug() << "cc" << sizeof(cc) << &cc;
    qDebug() << "dd" << sizeof(dd) << &dd;
    return a.exec();
}

输出结果:

aa 1 0x28fde7
bb 1 0x28fde6
cc 1 0x28fde5
dd 1 0x28fde4

根据网上的说法:这个隐晦的1是编译器安插进去的一个char,使得2个空的struct或者class在内存中具有独一无二的地址

#include "mainwindow.h"
#include <QApplication>
#include <QtDebug>

struct STR
{
    
    
    char a[0];
};

class Test
{
    
    
public:
    Test() {
    
    }
    char a[0];
};

int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);
    STR aa,bb;
    Test cc,dd;
    qDebug() << "aa" << sizeof(aa) << &aa;
    qDebug() << "bb" << sizeof(bb) << &bb;
    qDebug() << "cc" << sizeof(cc) << &cc;
    qDebug() << "dd" << sizeof(dd) << &dd;
    return a.exec();
}

输出结果:

aa 0 0x28fde8
bb 0 0x28fde8
cc 0 0x28fde8
dd 0 0x28fde8

编译器指定一块空的地址,所有空内存对象都指向这个地址。

猜你喜欢

转载自blog.csdn.net/sinat_33859977/article/details/99839325