What does the “padding class ‘Tester’ with 4 bytes” warning mean?

There’s no real problem here. In C and C++, the compiler is allowed to insert padding after struct members to provide better alignment, and thus allow faster memory access. In this case, it looks like has decided to place smap on an 8-byte alignment. Since an int is almost certainly four bytes, the warning is telling you that there are four bytes of wasted space in the middle of the struct.

If there were more members of the struct, then one thing you could try would be to switch the order of the definitions. For example, if your Tester had members:

 struct Tester {
     int foo;
     std::map<int, int> smap;
     int bar;

then it would make sense to place the two ints next to each other to optimise alignment and avoid wasted space. However, in this case, you only have two members, and if you switch them around then the compiler will probably still add four bytes of padding to the end of the struct in order to optimise the alignment of Testers when placed inside an array.

Leave a Comment