尽管基为空,为什么多重继承会增加对象的大小? [英] Why does multiple inheritance increase the size of the object despite the bases being empty?
问题描述
给出以下代码:
#include <iostream>
struct A {
};
struct B {
};
struct C {
};
struct E : A {
int field;
};
struct F : A, B {
int field;
};
struct G : A, B, C {
int field;
};
int main() {
std::cout << _MSC_VER << std::endl;
std::cout << sizeof(E) << std::endl;
std::cout << sizeof(F) << std::endl;
std::cout << sizeof(G) << std::endl;
int o;
std::cin >> o;
return 0;
}
我得到以下输出:
1900
4
8
8
为什么F
和G
的基数为空,为什么它们的大小为8
?
为什么E
的大小也不会增加?
Why would F
and G
have sizes of 8
even though their bases are empty?
And why would the size of E
not increase as well?
我正在使用Visual Studio Community 2015版本14.0.25431.01 Update 3构建它.MSVC++版本显然是9.0.
I am building this with Visual Studio Community 2015, version 14.0.25431.01 Update 3. The MSVC++ version is apparently 9.0.
为什么?这种特殊的内存布局有什么原理?
How come? What rationale is there for such a peculiar memory layout?
推荐答案
Visual Studio 2015 Update 2添加了对空基类优化的支持.但是,由于更新之间应该与布局兼容,因此默认情况下不启用优化.您需要使用__declspec(empty_bases)手动请求.
Visual Studio 2015 Update 2 added support for Empty Base Class Optimization. However, as Updates are supposed to be layout-compatible between them, the optimization is not on by default; you need to manually ask for it using __declspec(empty_bases).
VC的博客中提供了更多信息: https://blogs.msdn.microsoft.com/vcblog/2016/03/30/optimizing-the-layout-of-empty-base-classes-in-vs2015-update-2-3 /
There's more information in VC's blog: https://blogs.msdn.microsoft.com/vcblog/2016/03/30/optimizing-the-layout-of-empty-base-classes-in-vs2015-update-2-3/
一旦他们发布了主要的编译器版本更新,并且允许他们破坏二进制兼容性,这最终将是默认设置.
This will eventually be the default once they release a major compiler version update, where they're allowed to break binary compatibility.
这篇关于尽管基为空,为什么多重继承会增加对象的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!