Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does multiple inheritance increase the size of the object despite the bases being empty?

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?

like image 488
Pythagoras of Samos Avatar asked Oct 31 '16 22:10

Pythagoras of Samos


2 Answers

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.

like image 86
Kerrek SB Avatar answered Nov 02 '22 02:11

Kerrek SB


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.

like image 21
ZaldronGG Avatar answered Nov 02 '22 02:11

ZaldronGG