cpp-struct-layout
C++ Struct Layout
Use this skill to audit a class, struct, or union for padding waste and propose a member ordering that minimizes sizeof without changing behavior. The canonical fix is to order non-static data members from largest alignment to smallest so the compiler inserts fewer alignment-padding bytes. Placing a small member such as std::uint16_t between two larger, more-strictly-aligned members forces internal padding to re-align the member that follows it; moving the small member to the end lets it share the struct's trailing slot instead. Whether that actually shrinks sizeof depends on the exact widths, so the rule is always: compute the before/after layout, then reorder (see How Padding Arises for a worked example).
The goal is a behavior-preserving layout change: same members, same types, same observable semantics, smaller (or equal) footprint and better cache density. Reordering members is the cheapest such change; this skill also flags when reordering is unsafe (ABI, wire formats, C interop, init-order dependencies).
UTILITY SKILL. INVOKES: read-only file access for supplied targets; no other tools or skills. FOR SINGLE OPERATIONS: use to reorder one type's members, audit a header for padding, or judge whether a proposed layout change is safe.
This skill is the deep, dedicated treatment of struct/union padding waste — the kind a brief clang-analyzer-optin.performance.Padding lint item only flags; cite that check in findings so the reader can enable it (-Xclang -analyzer-checker=optin.performance.Padding, or via clang-tidy).
Scope
- Use this skill for: non-static data member ordering to reduce internal and tail padding; identifying which member's alignment forces padding; estimating
sizeof/alignof/offsetofbefore and after a reorder; deciding whenalignas,[[no_unique_address]], or splitting hot/cold fields is warranted; spotting oversized members (e.g. anenumwith a needlessly wide underlying type, anintwherestd::uint8_tsuffices) that inflate alignment. - Apply it to: plain data aggregates, value types stored in large arrays/containers (where per-element padding multiplies), per-connection/per-request/per-message structs in a high-concurrency service (footprint × concurrency), and any type the user reports as "bigger than expected".
- Keep the change behavior-preserving: same set of members and types, same access semantics. Only the declaration order (and occasionally alignment qualifiers) changes.