Three Members Total 11 Bytes, but sizeof Is 24
Start with a simple class:
struct Frame {
char tag;
double value;
short code;
};
The three members total 11 bytes, yet sizeof(Frame) is 24. Where do the other 13 bytes come from?
They are padding. A compiler does not place members directly next to each other, because every member has an alignment requirement: its starting address must be a multiple of some integer. On x86-64, the address of a double must be a multiple of 8, so value cannot directly follow the 1-byte tag and has to start at offset 8. The 7 bytes in between belong to no member; they are the padding.
The 24 bytes of Frame are listed below. Every offset and size in this article comes from GCC and Clang on x86-64; other platforms may differ.
| Offset | Contents | Bytes |
|---|---|---|
| 0 | tag | 1 |
| 1–7 | Internal padding | 7 |
| 8–15 | value | 8 |
| 16–17 | code | 2 |
| 18–23 | Tail padding | 6 |
The gap between members is called internal padding; the gap at the end of the object is called tail padding. 11 + 7 + 6 = 24.
The number 24 is not specified by the C++ standard; the compiler and the platform decide it. The standard specifies only the rules, such as the one in the next section: sizeof is a multiple of the alignment requirement. The actual number of bytes depends on the platform.
Tail padding is not waste. It guarantees that every Frame is 24 bytes with an alignment requirement of 8, so that when Frame objects are arranged in an array, each element lands on an address that is a multiple of 8. A single Frame object is no different: whether it is a local variable or was created with new, it occupies 24 bytes.
This article is a sequel to What a C++ Object Looks Like in Memory: From Source Code to Bytes. The previous article showed how to observe what an object looks like in memory. This one deals only with how data members are arranged: where the two kinds of padding come from, the order of members, three tools for querying and controlling the layout, and three experiments that can be reproduced.
Where Internal Padding and Tail Padding Come From
Internal padding comes from the alignment requirements of members; value in the previous section is one example. Tail padding comes from arrays. The Record from the previous article (char tag; int count; double ratio;, 16 bytes) serves as an example. Add one member to it:
struct Record {
char tag; // offset 0
int count; // offset 4; 3 bytes of padding follow tag
double ratio; // offset 8
char note; // offset 16
};
The four members total 14 bytes. With the 3 bytes after tag, the data ends at offset 17. For a single object on its own, 17 bytes would seem to be enough.
But a Record can appear in an array. C++ requires array elements to be laid out contiguously, so the starting addresses of adjacent elements differ by exactly sizeof(Record). Suppose sizeof(Record) were 17: with the first element at address 0, the second would start at 17. The address of a Record must be a multiple of 8, and 17 is not. For every element in the array to satisfy the alignment requirement, sizeof(Record) must be a multiple of 8. The compiler therefore adds 7 bytes at the end, bringing the total to 24. These 7 bytes are the tail padding.
This reasoning holds for every type, which gives a general rule: sizeof(T) is always a multiple of alignof(T). How many bytes each kind of padding takes depends on the types and order of the members, and the compiler decides it. The same reasoning also explains empty classes: an object of a class with no data members still occupies at least 1 byte; otherwise two elements of an array would share the same address. Such a class usually occupies exactly 1 byte, and the same holds when it is a member of another class.
The Order of Members
With the size settled, the next topic is where the members go. The C++ standard specifies that, except in unions, the non-static data members of a class are arranged in declaration order, so that a member declared later has a higher address. The rule constrains only the order, not the spacing, so there can be padding between members.
The rule was revised once. Earlier standards left one exception: members within the same access-control section (for example, all under public:) were arranged in declaration order, but the compiler decided the order between different access-control sections. The authors of proposal P1847 noted that, to their knowledge, no implementation had ever used this freedom. C++23 removed the exception: no matter how the access-control sections are divided, members are arranged in declaration order. When the previous article says the standard “leaves freedom in the ordering of members in different access-control sections”, it is referring to this exception.
Access specifiers themselves do not affect the layout. public: and private: are compile-time access rules and occupy no bytes in the object. Whether the members are written in several access-control sections or in one, the result is the same. The only way to control the layout is to change the declaration order of the members.
A static data member does not occupy space in the object. The standard specifies that it is not part of the class object, and its storage belongs to no object. It can therefore be written anywhere in the member list without affecting the arrangement of the other members or increasing sizeof. Since C++17 it can also be declared inline static, defined and initialized inside the class, which removes the need for a definition outside the class. This does not affect the object layout either.
An empty member marked [[no_unique_address]] is an exception to the ordering rule above: it can share its address with another member, as explained later. In addition, if a class has virtual functions, the object contains an extra vtable pointer added by the compiler, usually at the start of the object; it is not a member declared by the programmer, but it takes up space all the same.
Querying and Controlling the Layout: offsetof, alignas, and [[no_unique_address]]
Now that the origin of the layout is clear, here are three tools: offsetof for querying offsets, alignas for raising alignment, and [[no_unique_address]] for saving space on empty members.
offsetof is a macro. offsetof(Frame, value) gives the byte offset of a member within the object; the result is 8. It is guaranteed to work only for standard-layout types. Standard layout means the structure of the class is simple enough that its members can be accessed directly, as in C. Most common classes are standard-layout. Three typical cases are not standard-layout: the class has virtual functions or virtual base classes; its members have inconsistent access control, for example some are public and some are private; or its members are split between a base class and a derived class. A class is also not standard-layout if a member is a reference, or if the type of a member is itself not standard-layout.
Frame is standard-layout. MixedAccess below is not, because its two members have different access control:
#include <type_traits>
struct Plain {
char tag;
double value;
};
struct MixedAccess {
int id;
private:
double value; // access control differs from id
};
static_assert(std::is_standard_layout_v<Plain>);
static_assert(!std::is_standard_layout_v<MixedAccess>);
Standard-layout types have one more property: the first member has the same address as the object itself, that is, its offset is 0; the only exception is a first member that is a bit-field. A standard-layout type can still have padding, and its size is not necessarily the sum of its members.
For types that are not standard-layout, offsetof should be avoided. Before C++17, using it was undefined behavior; since C++17, the standard allows compilers to support it, but does not guarantee that all compilers give the same result. In addition, static members, member functions, and bit-fields cannot be passed to offsetof: the result is undefined for the first two, and a bit-field has no byte offset.
alignas raises the alignment requirement. For example, a block of data that must be aligned to 64 bytes:
struct alignas(64) Block {
unsigned char data[8];
};
static_assert(alignof(Block) == 64);
static_assert(sizeof(Block) == 64);
Raising the alignment raises the size as well: 8 bytes of data are padded out to 64 bytes.
alignas has two restrictions: the alignment value must be a power of 2, and it cannot be lower than the type’s existing alignment. Code that violates either restriction is ill-formed, that is, invalid:
// alignas(7) char x; // ill-formed: 7 is not a power of 2
// alignas(2) double x; // ill-formed: double requires 8-byte alignment and cannot be lowered to 2
A type whose alignment requirement exceeds alignof(std::max_align_t) is called an over-aligned type; Block above is one. Here std::max_align_t stands for the strictest alignment among the fundamental types, which is 16 on this platform. Whether the compiler supports that high an alignment is implementation-defined, and where it is not supported, the code is likewise invalid.
Dynamic allocation has to meet the same alignment requirement. Since C++17, new automatically switches to the operator new overload that takes an alignment argument for over-aligned types, and the matching operator delete is used on release. So as long as the class does not define its own operator new, plain new is enough. Earlier standards had no such mechanism, and an over-aligned object created with new was not guaranteed to meet its alignment requirement.
[[no_unique_address]] saves space on empty members. Some classes have behavior but no data, such as the comparators and allocators of containers. If such an empty class is handled as an ordinary member, it still takes 1 byte and makes the object larger for no reason. This C++20 attribute exists for exactly that case:
struct Empty {};
struct TwoEmpties {
[[no_unique_address]] Empty first;
[[no_unique_address]] Empty second;
char c;
};
With the attribute, the compiler can let an empty member share its address with another member. In the example above, sizeof(TwoEmpties) is 2: first and c are both at offset 0, and second is at offset 1. c is declared last yet shares offset 0 with first, because the attributed empty member has zero size and the ordering rule given earlier does not apply to it. Without the attribute, the size is 3.
Precisely, the attribute allows a member to share its address with other members (or base classes) of the same object; the standard calls such a member a potentially-overlapping subobject. It is a permission, not a guarantee, and the compiler may ignore it. It also has a limit: two members of the same type cannot share an address, which is why first and second in the example above each take 1 byte and the size is 2 rather than 1.
Compiler support also varies. MSVC ignores the standard spelling; only [[msvc::no_unique_address]] takes effect. When using this attribute, test it on the target compiler.
Three Experiments: Reordering Members, Arrays, and Bit-fields
Three experiments verify the rules above.
First experiment: the members stay the same; only the declaration order changes.
struct Loose {
char tag; // offset 0
double value; // offset 8; 7 bytes of padding follow tag
char state; // offset 16
int count; // offset 20; 3 bytes of padding follow state
};
struct Packed {
double value; // offset 0
int count; // offset 8
char tag; // offset 12
char state; // offset 13
};
static_assert(sizeof(Loose) == 24);
static_assert(sizeof(Packed) == 16);
Loose puts the double between two chars: 7 bytes are left empty before the double, and the int after it leaves 3 more empty for alignment, for a total of 24 bytes. Packed puts the double, which has the strictest alignment requirement, first, then the int, then the two chars. There is no gap in between; only 2 bytes are added at the end, for a total of 16 bytes.
| Internal padding | Tail padding | Size | |
|---|---|---|---|
Loose | 10 bytes | 0 | 24 bytes |
Packed | 0 | 2 bytes | 16 bytes |
The two classes have exactly the same members; the order alone saves 8 bytes. The rule is to put the members with the stricter alignment requirements first. The compiler does not reorder members automatically, because it must follow the declaration order. Clang’s -Wpadded option reports where padding is inserted, which makes it easy to check.
Second experiment: the cost of tail padding in an array.
struct Item {
int value; // offset 0
char tag; // offset 4; 3 bytes of padding follow it
};
static_assert(sizeof(Item) == 8);
static_assert(sizeof(Item[4]) == 32);
Item has only 5 bytes of members, yet each object is 8 bytes. An array of four elements is 32 bytes in total, 12 of which are padding. The same applies to internal padding: adjacent elements in an array are a whole object apart, and each element carries its own padding. This cost cannot be removed, because a shorter spacing would leave the later elements misaligned. The only practical remedy is to adjust the declaration order so that there is as little padding as possible.
Third experiment: bit-fields. unsigned a : 3 specifies that the member occupies only 3 bits, which is often used to save space:
struct Flags {
unsigned a : 3;
unsigned b : 5;
unsigned c : 9;
};
struct Separated {
unsigned a : 3;
unsigned : 0; // unnamed zero-width bit-field
unsigned b : 5;
};
Bit-fields do save space, but their arrangement is almost entirely up to the compiler. Whether adjacent bit-fields are packed into the same storage unit (for example, the same unsigned), whether they may straddle units, and whether bits are filled starting from the high end or the low end are all implementation-defined. An unnamed bit-field also takes up space; the program simply cannot access it. An unnamed bit-field of width 0 allocates no bits at all; it only forces the next bit-field to start at a new storage unit.
Bit-fields are therefore suited to saving space on flags inside a program, and unsuited to defining the layout of network packets, file formats, or shared memory. Those cases require an exact bit layout, and the encoding and decoding should be written explicitly. The same applies to bool bit-fields: do not assume they have the same representation as unsigned bit-fields.
To conclude:
sizeof(T)is a multiple ofalignof(T), so there may be tail padding at the end of an object.- Members are arranged in declaration order, regardless of access-control sections since C++23. To save space, the declaration order has to be adjusted by hand.
offsetofis guaranteed to work only for standard-layout types.alignascannot lower an existing alignment; dynamic allocation of over-aligned types is only guaranteed since C++17.[[no_unique_address]]can make an empty member take no space, but compiler support varies, so test it before relying on it.- The arrangement of bit-fields varies by compiler, so they should not be used to define external formats.
Returning to the Frame from the beginning: 11 bytes are members, 7 bytes are given up for the alignment of the double, and 6 bytes are added so that the object can sit in an array. Every number has a reason.