0

Why is the following not working?

If sizeof(B) is 8, so sizeof(C) should also be 8 since it's inheriting from a single classe, EBO should've been still be used here.

Do I really have to use __declspec(empty_bases) here? :/

struct A {};

struct B : A {
    size_t x;
};

struct C : A {
    B b;
};

int
main() {

    static_assert(sizeof(C) == sizeof(size_t));

    return 0;
}
João Pires
  • 927
  • 1
  • 5
  • 16
  • 3
    Did you intend to compare sizeof(C) == sizeof(B)? – negacao Feb 08 '21 at 12:13
  • Yes, that's the intentation – João Pires Feb 08 '21 at 12:16
  • This doesn't work in g++ either: [**Live demo on coliru**](http://coliru.stacked-crooked.com/a/dea3bb2df5cb8f2f) – Scheff's Cat Feb 08 '21 at 12:18
  • but that still doesnt tell you if empty base class optimization was applied. You would have to compare `sizeof(C)` to `sizeof` a `struct D { B b; }`, but I think even that cannot tell you reliably if ebo was applied or not – 463035818_is_not_an_ai Feb 08 '21 at 12:18
  • "If sizeof(B) is 8, so sizeof(C) should also be 8 " you make the assumption that `sizeof(C)` is size of members + size of base class, but also without the base class `sizeof(C)` is not necessary `sizeof(B)` – 463035818_is_not_an_ai Feb 08 '21 at 12:20
  • @largest_prime_is_463035818 Yes: [**Demo on coliru**](http://coliru.stacked-crooked.com/a/10a4c673117b5e07): `8 vs. 16` – Scheff's Cat Feb 08 '21 at 12:21
  • If I got it right, OPs case is similar like the `struct Derived2` in the (counter) example of [Empty base optimization](https://en.cppreference.com/w/cpp/language/ebo) (but it all made me dizzy a bit). – Scheff's Cat Feb 08 '21 at 12:26
  • Does anyone has any idea on how to shrink the size of the struct to its most absolute aligned minimum? – João Pires Feb 08 '21 at 12:45
  • It looks like you get what you expect if C is derived from a different empty class. Possibly this is so that two different members of the same type do not share an address. – Hasturkun Feb 08 '21 at 15:20

0 Answers0