Search code examples
c++cpp-core-guidelines

Wasted space in layout in CPP Core Guidelines


I was reading CPP Core Guidelines, P.9: Don’t waste time or space:

Example, Bad:

struct X {
    char ch;
    int i;
    string s;
    char ch2;

    X& operator=(const X& a);
    X(const X&);
};

Then it states:

... Note that the layout of X guarantees that at least 6 bytes (and most likely more) are wasted.

Why 6 bytes are guaranteed to be wasted? And how could be fixed (except the constructor declaration whom are source of waste of the example)


Solution

  • The struct starts with a default alignment. The first member ch is aligned. i is an int and that must be four byte aligned (when int is four bytes long), so between ch and i you get three bytes padding. The same is true at the end of the struct after ch2 where you get three bytes of padding. These are inserted so that for a X x[2]; both elements are correctly aligned in memory.

    struct X {
        char ch;
        char padding1[3]; // so that int i is int-aligned (four bytes)
        int i;
        string s;
        char ch2;
        char padding2[3]; // end of struct must also be aligned
    };