C ++ POD结构继承?对派生成员的内存布局有任何保证 [英] C++ POD struct inheritance? Are there any guarantees about the memory layout of derived members

查看:187
本文介绍了C ++ POD结构继承?对派生成员的内存布局有任何保证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说,我有一个 struct RGB ,我想创建 struct RGBA ,它继承 RGB

Let's say, I have a struct RGB and I want to create struct RGBA, which inherits RGB:

struct RGB {
    unsigned char r;
    unsigned char g;
    unsigned char b;
};

struct RGBA: RGB {
    unsigned char a;
};

两者都将用于读取未压缩的图片数据:

Both will be used for reading uncompressed image data:

RGBA *pixel=static_cast<RGBA *>(image->uncompressed_data);


$ b ?是否有人保证:

Question: Is this safe, regarding the memory layout of struct RGBA? Does anyone guarantee, that:


  • unsigned char a $ c> RGB struct (不在之前)

  • struct RGB 参数从 struct RGBA

  • unsigned char a comes after the RGB struct (not before)
  • There is no padding between struct RGB and the a parameter from struct RGBA?

#pragma pack 帮助这里?

推荐答案

不,布局不能保证。唯一的保证是对于标准布局类;并且这种类的条件之一是它

No, the layout is not guaranteed. The only guarantees are for standard-layout classes; and one of the conditions of such a class is that it


在大多数派生类中没有非静态数据成员,具有非静态数据成员的一个基类或不具有非静态数据成员的基类

either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members

换句话说,所有数据成员必须在同一个类别中,而不能在同一个类别中。

In other words, all data members must be in the same class, not in more than one.

这篇关于C ++ POD结构继承?对派生成员的内存布局有任何保证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆