How to optimize object's memory size while using multiple inheritance with visual studio compiler?

你。 提交于 2019-12-25 06:45:41

问题


#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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!