C++内存对齐的问题

来源:百度知道 编辑:UC知道 时间:2024/05/16 18:12:33
#pragma pack(16)
class dd{
int a;
virtual ~dd(){}
double c;

virtual out(){}
};
#pragma pack()
内存中形式如下:
vptr:4字节
int:4字节
double 8字节,它们之间刚好不用填充数据,在结尾也不用填,所以
是16,可以执行结果是24!

它为什么不是16而是24呢?
回答详细有15分追加!
回答manyxyz:照你的说法,如果我将#pragma pack(16)
改正为#pragma pack(8),那么,它的大小会是16,但是事实上还是24,为什么呢?我是VC++6.0编译器,Intel P4 2.4G处理器,256MB内存,xp sp2操作系统
!

看错,
#pragma pack(n)的作用你还没理解透

这个n的值可以为1, 2, 4, 8, 16,pack的原则是尽量使其在内存中和机器的自然字长相同,你的机器自然字长可能是2字也就是4字节,所以当n > 4时,字节数小于4的类型会被自动填充为4字节,大于4字节的才根据n的指定来填充,所以你那个类的内存排列方式应该是这样:

vptr: 4, int 4, double 16;

我考虑过是否是编译器优化的结果,但我看了下发现我的编译器优化是被关掉的,而且struct和clas的对齐方式是默认default,所以得出以上结论,仅供参考!

受你问题的启发,这几研究了下计算机组成原理,其中看了一本书叫Write Great Code Vol1——Understanding The Machine,在内存结构那章有这么一段:

Figure 7-8 also suggests that compilers pack the fields into adjacent memory locations with no gaps between the fields. While this is true for many languages, this certainly isn't the most common memory organization for a record. For performance reasons, most compilers will actually align the fields of a record on appropriate memory boundaries. The exact details vary by language, compiler implementation, and CPU, but a typical compiler will place fields at an offset within the record's storage area that is 'natural' for that particular field'