Windows上具有联合和空基类的布局

鉴于以下程序:

#include <cstdio>
#include <type_traits>
#include <utility>

struct EmptyClass {};

template <typename T, typename U>
struct Storage {
 protected:
  union Union {
    T t;
    U u;
  } data;

  char flag = false;
};

class AnotherEmptyClass {};

template <typename T, typename U>
class Derived : private Storage<T, U>, public AnotherEmptyClass {};

static_assert(std::is_standard_layout_v<Derived<char, EmptyClass>>);

int main() {
  printf("Storage<char, EmptyClass>: %zun", sizeof(Storage<char, EmptyClass>));
  printf("Derived<char, EmptyClass>: %zun", sizeof(Derived<char, EmptyClass>));

  printf("Storage<char, char>: %zun", sizeof(Storage<char, char>));
  printf("Derived<char, char>: %zun", sizeof(Derived<char, char>));
}

这在 Linux 上输出 2 2 2 2,但在 Windows 上输出 2 3 2 2(使用 clang 和 MSVC)。

这是为什么?似乎使用EmptyClass作为联合的成员可以防止派生类上的空基类优化。但是对于标准布局类型,需要空基类优化。或者这种布局有不同的原因吗?

以上是Windows上具有联合和空基类的布局的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>