问题
#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 above code using cl, the output is '8'. While compiling with g++, the output will be '4'.
Without multiple inheritance the output will be '4' with both compilers.
Thanks.
回答1:
Here is the answer why it is 8-byte: Why empty base class optimization is not working?
The solution is to chain all 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 pattern in "boost/operators.hpp"
来源:https://stackoverflow.com/questions/24722070/how-to-optimize-objects-memory-size-while-using-multiple-inheritance-with-visua