Skip to content
LeetQuant
E12 Advanced C++

E12 · Advanced C++ · Lesson 4 of 5

The Object Model

How objects are laid out in memory: alignment and padding with real printed sizes, the empty base optimisation, the vptr and vtable as Clang builds them, the costs of multiple and virtual inheritance, and when memcpy on an object is legal.

20 min

Objects are bytes with rules

The object model is the part of C++ that decides where every byte of an object goes. You need it to answer "what is sizeof this struct?", "what does a virtual call compile to?", "why did casting this pointer change its value?" and "can I memcpy this into a shared-memory ring?". The rules come from two places: the standard (alignment, member order, which types are trivially copyable) and the platform ABI. macOS and Linux both use the Itanium C++ ABI for layout and vtables; Windows (MSVC) differs in details.

Sizes below are from Apple clang 17 on arm64 with libc++, compiled with c++ -std=c++20 -O2 -Wall. Clang can print its own layout decisions with -Xclang -fdump-record-layouts and -Xclang -fdump-vtable-layouts; several outputs below come from those flags.

Alignment and padding

Every type has an alignment alignof(T), a power of two; an object must start at an address that is a multiple of it. For a struct:

  1. Non-static members are placed in declaration order (the compiler may not reorder them), each at the next offset that is a multiple of its alignment.
  2. The struct's alignment is the largest member alignment.
  3. sizeof is rounded up to a multiple of the struct's alignment, so that in an array every element is aligned.
#include <cstddef>
#include <cstdint>
#include <cstdio>

struct Bad  { char side; double px; char tif; std::int32_t qty; char flag; };   // declaration order
struct Good { double px; std::int32_t qty; char side, tif, flag; };             // largest first

struct Empty {};
struct WithEmptyMember { Empty e; int x; };
struct WithEmptyBase : Empty { int x; };
struct WithNUA { [[no_unique_address]] Empty e; int x; };

#define SHOW(T) std::printf("%-16s sizeof %2zu  alignof %zu\n", #T, sizeof(T), alignof(T))

int main() {
    SHOW(Bad); SHOW(Good);
    std::printf("Bad offsets: side %zu px %zu tif %zu qty %zu flag %zu\n",
                offsetof(Bad, side), offsetof(Bad, px), offsetof(Bad, tif), offsetof(Bad, qty), offsetof(Bad, flag));
    std::printf("Good offsets: px %zu qty %zu side %zu tif %zu flag %zu\n",
                offsetof(Good, px), offsetof(Good, qty), offsetof(Good, side), offsetof(Good, tif), offsetof(Good, flag));
    SHOW(Empty); SHOW(WithEmptyMember); SHOW(WithEmptyBase); SHOW(WithNUA);
}
Bad              sizeof 32  alignof 8
Good             sizeof 16  alignof 8
Bad offsets: side 0 px 8 tif 16 qty 20 flag 24
Good offsets: px 0 qty 8 side 12 tif 13 flag 14
Empty            sizeof  1  alignof 1
WithEmptyMember  sizeof  8  alignof 4
WithEmptyBase    sizeof  4  alignof 4
WithNUA          sizeof  4  alignof 4

Walk through Bad: side at 0; px needs 8-alignment, so 7 bytes of padding and px at 8; tif at 16; qty needs 4-alignment, so 3 bytes of padding and qty at 20; flag at 24; the size is rounded from 25 up to 32. That is 17 bytes of data in 32. Good sorts members by decreasing alignment: 8+4+3=158 + 4 + 3 = 15 bytes of data, rounded to 16. Same fields, half the memory.

The empty-class rows: an empty class has sizeof 1, because distinct objects must have distinct addresses. As a member that byte costs a full alignment slot (WithEmptyMember is 8). As a base class it can take zero bytes, the empty base optimisation (WithEmptyBase is 4). C++20's [[no_unique_address]] gives the same saving for a member.

Worked example

what does field order cost a ten-million-order book?

A simulator keeps 10 million resting orders in a std::vector. Compare Bad and Good above on total memory and on orders per 64-byte cache line, and say what you would add to the code to stop the layout regressing.

Show solution

Memory. 107×32=3.2×10810^{7} \times 32 = 3.2 \times 10^{8} bytes (320 MB) for Bad against 107×16=1.6×10810^{7} \times 16 = 1.6 \times 10^{8} bytes (160 MB) for Good.

Cache lines. A 64-byte line holds 64/32=264 / 32 = 2 Bad orders or 64/16=464 / 16 = 4 Good ones. A scan over all orders (say, to find those to expire) touches 107/2=5×10610^{7} / 2 = 5 \times 10^{6} lines against 2.5×1062.5 \times 10^{6}: half the memory traffic for a bandwidth-bound loop.

Guarding it. Put static_assert(sizeof(Order) == 16); and, if the struct crosses a process boundary, static_assert(offsetof(Order, qty) == 8); next to the definition, so a new field added in the wrong place fails the build. Clang's -Wpadded warning lists every padding hole if you want the compiler to audit a header.

Reordering is not free in one case: if two fields are always used together, keeping them adjacent may matter more than a few bytes of padding. Decide by access pattern, then by size.

Empty bases in the standard library

The empty base optimisation is why stateless policy objects are free. libc++ stores a unique_ptr's deleter in a compressed pair; an empty deleter class costs nothing, while a function-pointer deleter is a real 8-byte member:

unique_ptr<int>                     8
unique_ptr<int, FreeDeleter>        8
unique_ptr<int, void(*)(int*)>      16
shared_ptr<int>                     16
std::string                         24
std::vector<int>                    24
std::function<void()>               32
std::optional<double>               16
std::variant<int, double>           16

(Program: one std::printf of sizeof per line.) The other rows are libc++ on 64-bit: std::string is three words with a short-string buffer inside them, std::vector is three pointers (begin, end, capacity end), and shared_ptr is two pointers (object and control block). These are implementation sizes: libstdc++ on Linux has a 32-byte std::string, for example. In an interview, give the reasoning ("three pointers") rather than a number you cannot justify.

The vptr and the vtable

A class with at least one virtual function gets a hidden pointer, the vptr, at offset 0 (in the Itanium ABI), pointing into a per-class table of function pointers, the vtable. Constructors set the vptr; that is why polymorphic objects are never trivially copyable.

struct Pricer { virtual ~Pricer() = default; virtual double price(double s) const = 0; };
struct Linear final : Pricer { double k = 2; double price(double s) const override { return k * s; } };

double via_base(const Pricer& p, double s)  { return p.price(s); }   // virtual call
double via_final(const Linear& p, double s) { return p.price(s); }   // final: devirtualised, inlined

Clang's vtable dump for Linear:

Vtable for 'Linear' (5 entries).
   0 | offset_to_top (0)
   1 | Linear RTTI
       -- (Linear, 0) vtable address --
       -- (Pricer, 0) vtable address --
   2 | Linear::~Linear() [complete]
   3 | Linear::~Linear() [deleting]
   4 | double Linear::price(double) const

The vptr points at entry 2, after the offset-to-top and RTTI slots. There are two destructor entries: "complete" destroys the object, "deleting" also frees it (that is what delete p calls). price is entry 4, which is 2×8=162 \times 8 = 16 bytes past the vptr. The arm64 code at -O2:

via_base:                      via_final:
    ldr  x8, [x0]                  ldr  d1, [x0, #8]
    ldr  x1, [x8, #16]             fmul d0, d1, d0
    br   x1                        ret

via_base loads the vptr, loads the function pointer at offset 16, and makes an indirect tail-call. In via_final the compiler knows the dynamic type cannot be anything but Linear, because the class is final, so it devirtualises and inlines: load k (at offset 8, after the vptr) and multiply. The direct cost of a virtual call is small when the branch predicts well; the real cost is the lost inlining.

The size cost: sizeof a struct with one int64_t is 8; add a virtual function and it is 16.

Multiple inheritance: two vptrs and pointer adjustment

#include <cstdint>
#include <cstdio>

struct Plain   { std::int64_t id; };
struct Poly    { virtual ~Poly() = default; virtual double price() const { return 0; } std::int64_t id; };

struct Feed    { virtual ~Feed() = default; virtual void on_quote() {} std::int64_t seq = 0; };
struct Logger  { virtual ~Logger() = default; virtual void log() {} std::int64_t lines = 0; };
struct Handler : Feed, Logger { void on_quote() override {} void log() override {} std::int64_t x = 0; };

struct Base    { std::int64_t b = 0; };
struct L : virtual Base { std::int64_t l = 0; };
struct R : virtual Base { std::int64_t r = 0; };
struct Diamond : L, R { std::int64_t d = 0; };
struct NvL : Base { std::int64_t l = 0; };
struct NvR : Base { std::int64_t r = 0; };
struct NvDiamond : NvL, NvR { std::int64_t d = 0; };

int main() {
    std::printf("Plain %zu, Poly %zu\n", sizeof(Plain), sizeof(Poly));
    std::printf("Feed %zu, Logger %zu, Handler %zu\n", sizeof(Feed), sizeof(Logger), sizeof(Handler));
    Handler h;
    Handler* hp = &h;
    Logger* lp = hp;                          // implicit upcast adjusts the pointer
    std::printf("Logger* - Handler* = %td bytes\n",
                reinterpret_cast<char*>(lp) - reinterpret_cast<char*>(hp));
    std::printf("Diamond %zu (one Base), NvDiamond %zu (two Bases)\n", sizeof(Diamond), sizeof(NvDiamond));
}
Plain 8, Poly 16
Feed 16, Logger 16, Handler 40
Logger* - Handler* = 16 bytes
Diamond 48 (one Base), NvDiamond 40 (two Bases)

The layout dump explains the 40 bytes and the 16-byte adjustment:

         0 | struct Handler
         0 |   struct Feed (primary base)
         0 |     (Feed vtable pointer)
         8 |     std::int64_t seq
        16 |   struct Logger (base)
        16 |     (Logger vtable pointer)
        24 |     std::int64_t lines
        32 |   std::int64_t x
           | [sizeof=40, dsize=40, align=8,
           |  nvsize=40, nvalign=8]

Handler contains a whole Feed subobject (with its vptr) at 0 and a whole Logger subobject (with its own vptr) at 16. A Logger* must point at a Logger, so converting Handler* to Logger* adds 16 to the address (and a null pointer stays null, so the compiler emits a null check). This is why reinterpret_cast between base and derived pointers is wrong with multiple inheritance, and why two pointers to the same object can compare unequal as integers.

Virtual calls through the Logger* need the opposite adjustment, so the second half of Handler's vtable holds thunks:

Vtable for 'Handler' (11 entries).
   0 | offset_to_top (0)
   1 | Handler RTTI
       -- (Feed, 0) vtable address --
       -- (Handler, 0) vtable address --
   2 | Handler::~Handler() [complete]
   3 | Handler::~Handler() [deleting]
   4 | void Handler::on_quote()
   5 | void Handler::log()
   6 | offset_to_top (-16)
   7 | Handler RTTI
       -- (Logger, 16) vtable address --
   8 | Handler::~Handler() [complete]
       [this adjustment: -16 non-virtual] method: Logger::~Logger()
   9 | Handler::~Handler() [deleting]
       [this adjustment: -16 non-virtual] method: Logger::~Logger()
  10 | void Handler::log()
       [this adjustment: -16 non-virtual] method: void Logger::log()

Entry 10 says: when log() is called through the Logger subobject, subtract 16 from this and then run Handler::log. offset_to_top (-16) is what dynamic_cast<void*> uses to find the start of the full object.

Virtual inheritance: one shared base, paid for with indirection

In a diamond, ordinary inheritance gives two copies of the shared base; virtual inheritance gives one. The layouts (from dia.cpp, which declares Diamond : L, R with L and R both virtual Base, and NvDiamond the same without virtual):

         0 | struct Diamond
         0 |   struct L (primary base)
         0 |     (L vtable pointer)
         8 |     std::int64_t l
        16 |   struct R (base)
        16 |     (R vtable pointer)
        24 |     std::int64_t r
        32 |   std::int64_t d
        40 |   struct Base (virtual base)
        40 |     std::int64_t b
           | [sizeof=48, dsize=48, align=8,
           |  nvsize=40, nvalign=8]

NvDiamond is 40 bytes with Base at offsets 0 and 16 (two copies, and nd.b is ambiguous). Diamond has one Base, at offset 40, but it is 48 bytes, because L and R each gained a vptr even though nothing is virtual except the inheritance. The vtable stores the offset to the virtual base, since it differs between a standalone L and an L inside a Diamond. Every access to Base through an L& therefore costs a load of the vptr and of the offset before the load of the member.

Costs to name in an interview: bigger objects, an extra indirection for virtual-base access, the most-derived class must construct the virtual base, and a cast from a virtual base to a derived class needs dynamic_cast. Most low-latency code avoids virtual inheritance entirely.

Trivially copyable types and memcpy

A type is trivially copyable if its copy and move constructors, copy and move assignment operators are trivial or deleted (at least one not deleted), and its destructor is trivial: no user-provided versions, no virtual functions, no virtual bases, and the same for all members and bases. For such types, copying the bytes is copying the object, so memcpy into a buffer and back is well defined. This is the property that shared-memory rings, binary market-data decoders and std::bit_cast rely on.

#include <bit>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <type_traits>

struct Quote { std::int64_t bid, ask; std::int32_t bid_qty, ask_qty; };
struct Named { std::string sym; std::int64_t px; };
struct Virt  { virtual ~Virt() = default; std::int64_t px; };
struct UserCopy { std::int64_t px; UserCopy() = default; UserCopy(const UserCopy& o) : px(o.px) {} };

static_assert(std::is_trivially_copyable_v<Quote>);
static_assert(!std::is_trivially_copyable_v<Named>);     // std::string owns heap memory
static_assert(!std::is_trivially_copyable_v<Virt>);      // vptr must be set by a constructor
static_assert(!std::is_trivially_copyable_v<UserCopy>);  // even a do-nothing-special copy ctor counts
static_assert(std::is_standard_layout_v<Quote> && std::is_trivially_copyable_v<double>);

int main() {
    unsigned char wire[sizeof(Quote)];
    Quote q{10'000, 10'002, 5, 7};
    std::memcpy(wire, &q, sizeof q);           // serialise: fine for trivially copyable types
    Quote back;
    std::memcpy(&back, wire, sizeof back);     // deserialise: also fine, and the right way to "cast"
    std::printf("%lld %lld %d %d\n", (long long)back.bid, (long long)back.ask, back.bid_qty, back.ask_qty);

    std::uint64_t bits = std::bit_cast<std::uint64_t>(1.0);  // C++20: constexpr-friendly memcpy
    std::printf("bits of 1.0 = 0x%016llX\n", (unsigned long long)bits);
}
10000 10002 5 7
bits of 1.0 = 0x3FF0000000000000

UserCopy is the subtle one: its copy constructor does exactly what the default would, but because it is user-provided the type is no longer trivially copyable. = default keeps it trivial.

Breaking the rule compiles cleanly (-Wall said nothing) and fails at run time. Copying a std::string member byte-wise makes two objects own the same heap buffer:

#include <cstdio>
#include <cstring>
#include <string>

struct Named { std::string sym; long px; };

int main() {
    Named a{"A_SYMBOL_NAME_LONGER_THAN_THE_SSO_BUFFER", 1}, b;
    std::memcpy(static_cast<void*>(&b), &a, sizeof a);   // UB: Named is not trivially copyable
    std::printf("%s\n", b.sym.c_str());
    std::fflush(stdout);
}   // a and b now own the same heap buffer; both destructors free it

The run printed A_SYMBOL_NAME_LONGER_THAN_THE_SSO_BUFFER and was then killed with SIGTRAP (exit status 133) during destruction, when the second destructor freed the already freed buffer. With a string short enough for the inline buffer it would have appeared to work, which is how this bug survives testing.

Knowledge check

On a typical 64-bit platform, what is sizeof(S) for struct S { char a; double b; char c; }; and what is it after reordering to { double b; char a; char c; }?

Knowledge check

struct Handler : Feed, Logger, where both bases have virtual functions. Converting a Handler* to Logger* changed the address by 16 bytes. Why?

Knowledge check

Which type can be safely written to a shared-memory ring with memcpy and read back with memcpy in another process running the same binary?

Key takeaways

  • Members are laid out in declaration order at multiples of their alignment; sizeof is padded to the struct's alignment. Order by decreasing alignment and pin sizes with static_assert.
  • Empty classes cost a byte as members but nothing as bases or [[no_unique_address]] members; that is why stateless deleters and allocators are free.
  • A polymorphic object starts with a vptr; a virtual call is two loads and an indirect branch. final lets the compiler devirtualise and inline.
  • Multiple inheritance gives one vptr per polymorphic base, pointer adjustment on casts, and thunks; virtual inheritance adds vptrs and an indirection to reach the shared base.
  • Only trivially copyable types may be copied with memcpy or std::bit_cast; a user-provided copy constructor or a virtual function disqualifies a type.
  • Use -Xclang -fdump-record-layouts and -fdump-vtable-layouts to see Clang's decisions instead of guessing.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).