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

后端 未结 2 742
一个人的身影
一个人的身影 2021-01-17 09:06

Given this code:

#include 

struct A {

};

struct B {

};

struct C {

};

struct E : A {
    int field;
};

struct F : A, B {
    int field         


        
相关标签:
2条回答
  • 2021-01-17 09:34

    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.

    0 讨论(0)
  • 2021-01-17 09:38

    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.

    0 讨论(0)
提交回复
热议问题