c++ - 如何在使用 Visual Studio 编译器使用多重继承时优化对象的内存大小?

标签 c++ visual-studio-2012

#include <iostream>
class A {};
class B {};
class C : public A, public B {
    int a;
};

int main() {
    std::cout << sizeof(C) << std::endl;
    return 0;
}

如果我使用 cl 编译以上代码,输出为“8”。使用 g++ 编译时,输出将为“4”。

如果没有多重继承,两个编译器的输出都是“4”。

谢谢。

最佳答案

这是 8 字节的答案:Why empty base class optimization is not working?

解决方案是链接所有基类。为了优雅,我们可以这样写:

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; };

您可以在“boost/operators.hpp”中找到此模式的更多代码

关于c++ - 如何在使用 Visual Studio 编译器使用多重继承时优化对象的内存大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24722070/

相关文章:

C++ 构造函数实现错误

c++ - clang 5:std::optional 实例化参数类型的 std::is_constructible 特征

c++ - for 循环中的奇怪行为 - 一个错误?

c# - MySQL SELECT UNION 在单列上不同

image - 保存 CImage 给出错误 : identifier "ImageFormatJPEG" is undefined

sql-server - SSDT 架构比较锁 SET QUOTED_IDENTIFIER 为 OFF

模板中不允许使用 C++ 默认参数?

c++ - 尝试理解编译器错误信息 : default member initializer required before the end of its enclosing class

c# - WP8 定义多个预处理器值

c++ - 查找点属于哪个三角形的优化技巧