How to optimize object memory size when using multiple inheritance using Visual Studio compiler?

#include <iostream> class A {}; class B {}; class C : public A, public B { int a; }; int main() { std::cout << sizeof(C) << std::endl; return 0; } 

If I compile the code above with cl, the output will be "8". When compiling with g ++, the output will be "4".

Without multiple inheritance, the output will be "4" with both compilers.

Thanks.

0
source share
1 answer

Here's the answer, why is it 8-byte: Why does empty base class optimization not work?

The solution is to combine all the base classes. To be elegant, we could write like this:

 template <class Base = empty_base> class A1 : public Base {}; template <class Base = empty_base> class A2 : public Base {}; template <class Base =empty_base> class A3 : public Base {}; class C : public A1<A2<A3> > { int c; }; 

You can find more code in this template in "boost / operator.hpp"

+1
source

Source: https://habr.com/ru/post/976433/


All Articles