File tree Expand file tree Collapse file tree
documents/vol2-modern-features/ch07-attributes Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -143,12 +143,26 @@ struct Empty {
143143};
144144
145145struct Container {
146- Empty e; // sizeof(Empty) == 1,浪费
146+ // 在x86-64架构上常见内存布局为
147+ // offset 0: e (1 字节)
148+ // offset 1~ 3: padding (3 字节)
149+ // offset 4~ 7: x (4 字节)
150+ // 因为 int类型大小为4字节所以编译器通常
151+ // 会将它放在4的倍数的内存地址
152+ Empty e;
153+ int x;
154+ };
155+
156+ struct [[ gnu::packed]] PackedContainer {
157+ // offset 0: e (1 字节)
158+ // offset 1~ 4: x (4 字节)
159+ Empty e;
147160 int x;
148161};
149162
150163static_assert(sizeof(Empty) == 1);
151- static_assert(sizeof(Container) == sizeof(int) + 1); // 可能有 padding
164+ static_assert(sizeof(Container) == 8); // 大概率有padding
165+ static_assert(sizeof(PackedContainer) == sizeof(int) + 1); // 提示编译器不要添加padding
152166```
153167
154168对于大多数应用来说浪费 1 字节不算什么,但在泛型编程中,策略类(allocator、mutex policy 等)经常是空类。如果多个策略类同时作为成员,每个都占 1 字节,累积起来就不容忽视了。更关键的是,这会让 `sizeof` 的结果不符合预期,影响缓存行对齐等优化。
You can’t perform that action at this time.
0 commit comments