跳转至

cpp#

Struct Alignment Specify

在上一篇《Struct Alignment Rule》中,我们梳理了结构体存储布局的“地址边界对齐限制”规则。
本篇介绍通过编译器 gcc/msvc 提供的扩展特性及 C/C++ 提供的一些语言特性来修改默认的对齐参数,并测试分析其作用效果。

  1. The packed attribute specifies that a structure member should have the smallest possible alignment.
  2. The aligned attribute specifies a minimum alignment for the variable or structure field, measured in bytes.
  3. -fpack-struct[=n]/#pragma pack(n) specifies the maximum alignment, structure members can potentially be unaligned.

Struct Alignment Rule

An object doesn't just need enough storage to hold its representation. In addition, on some machine architectures, the bytes used to hold it must have proper alignment for the hardware to access it efficiently.

Where alignment most often becomes visible is in object layouts: sometimes structs contain "holes" to improve alignment.

C/C++ Memory Alignment

One of the low-level features of C/C++ is the ability to specify the precise alignment of objects in memory to take maximum advantage of a specific hardware architecture. By default, the compiler aligns class and struct members on their size value.

C++ Data Types

Every name and every expression has a type that determines the operations that may be performed on it.

Types built out of the built-in types using C++’s abstraction mechanisms are called user-defined types. They are referred to as structures, classes and enumerations.