Today at work we were optimizing memory usage. At some moment we found out that size (on stack) of our basic data structures is x bytes bigger than summed size of their members. Every basic data structure was written following Alexandrescu policy based design – using inheritance from some templated empty classes. Let’s see a simple example:
class A { };
class B { };
class C : public A, B
{
int test;
};
int main()
{
printf( "%d\n", sizeof( C ) );
return 0;
}
Compiler uses 4 byte aligment. Will this program print 4? That depends. Compiled by GCC it will print 4, but compiled by VC++ (2005-2010) it will print 8.
Every class in C++ has to be at least 1 byte of size in order to have a valid memory adress. With multiple inheritance sizeof(C) = sizeof(A) + sizeof(B) + some aligment. So VC++ behavior is correct, but not optimal. It’s strange that it was reported to MS in 2005 and still they didn’t fix it.