首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解gcc/clang与msvc2015在继承多个空类时的不同填充规则

理解gcc/clang与msvc2015在继承多个空类时的不同填充规则
EN

Stack Overflow用户
提问于 2018-04-01 03:46:01
回答 1查看 224关注 0票数 2

在gcc/clang msvc2015中,当涉及到空类的多重继承时,我看到了不同的行为。我在想,是否有人会知道标准中允许这种差异的是什么。

代码语言:javascript
复制
#include <cstdint>
using namespace std;

class Empty1 {};
static_assert(sizeof(Empty1) == 1, "Expected size of 1 for Empty1");

class Empty2 {};
static_assert(sizeof(Empty2) == 1, "Expected size of 1 for Empty2");

class Empty3 : Empty2, Empty1 {};
static_assert(sizeof(Empty3) == 1, "Expected size of 1 for Empty3");

class Int1 { uint32_t i; };
static_assert(sizeof(Int1) == 4, "Expected size of 4 for Int1");

class Int2 : Empty1 { uint32_t i; };
static_assert(sizeof(Int2) == 4, "Expected size of 4 for Int2");

class Int3 : Empty2 { uint32_t i; };
static_assert(sizeof(Int3) == 4, "Expected size of 4 for Int3");

class Int4 : Empty3 { uint32_t i; };
static_assert(sizeof(Int4) == 8, "Expected size of 8 for Int4");
static_assert(sizeof(Int4) == 4, "Expected size of 4 for Int4");

此代码在msvc2015上生成:

代码语言:javascript
复制
error C2338: Expected size of 4 for Int4

而gcc和clang则产生了这样的结果:

代码语言:javascript
复制
error: static_assert failed "Expected size of 8 for Int4"

换句话说,msvc2015在从空类继承时不会添加任何字节,但是在从多个类继承时会添加任何字节。在C++中是否存在未定义的行为?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-01 04:05:30

默认情况下,MSVC不进行此优化,因此其编译的代码可以与较早版本的编译器兼容。但是,__declspec(empty_bases),您可以告诉MSVC启用此优化:

代码语言:javascript
复制
#ifdef _MSC_VER
#define EBO_ENABLE __declspec(empty_bases)
#else
#define EBO_ENABLE
#endif

class EBO_ENABLE Empty3 : Empty2, Empty1 {};
static_assert(sizeof(Empty3) == 1, "Expected size of 1 for Empty3");

住在哥德波特

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49594604

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档