Given this code:
#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;
}
I am given the following output:
1900
4
8
8
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?
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?
There is no language rule that says that any particular type needs to have any particular size, with the exception of char
(size 1), and subject to the constraint that complete objects of class type have non-zero size. There is nothing buggy about your particular compiler's way of laying out the types in your example.
As for the new question, after you edited it: It's possible that MSVC just doesn't put a lot of effort into optimising multiple inheritance, because that's a comparatively rare thing that you could argue that there's little pay-off. I don't know anything about the real decision process that went on, but just consider that there may be pragmatic engineering trade-offs like this at play.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With