加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 派生类中的基类的大小

发布时间:2020-12-16 03:41:32 所属栏目:百科 来源:网络整理
导读:假设我没有数据类: struct Empty { /*some methods here*/}; 和派生类 struct Derived: Empty { int a; int b; char c; ....}__attribute__((packed));` 空类的对象具有size = 1.派生类的空部分通常具有0大小.据了解,编译器看到,基类空类没有数据,所以它可
假设我没有数据类:
struct Empty {
  /*some methods here*/
};

和派生类

struct Derived: Empty {
  int a;
  int b;
  char c;
  ....
}__attribute__((packed));`

空类的对象具有size = 1.派生类的空部分通常具有0大小.据了解,编译器看到,基类空类没有数据,所以它可以优化大小为空,以防它是“内部”派生,但不需要这样做的标准.

所以问题是:

我可以在编译时确定Derived类的空白部分并不真正占用内存.

我知道我可以像sizeof(Derived)= sizeof(a)sizeof(b)一样检查…但是它太冗长了,有几个类,如Derived.有更优雅的解决方案吗?

解决方法

您可以使用 std::is_empty来确保您继承的类是零大小:
static_assert(std::is_empty<Empty>{});

如果是,empty base optimization是guaranteed to take place for standard-layout classes.

I understand that I can do check like sizeof(Derived) = sizeof(a) + sizeof(b) ... But It is too verbose. Is there more elegant solution?

这不能正常工作,因为您需要考虑填充和最终属性(如打包).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读