C / C ++结构体内存布局当量 [英] C/C++ Struct memory layout equivalency

查看:108
本文介绍了C / C ++结构体内存布局当量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的C结构和C ++的struct声明:

Consider the following C struct and C++ struct declarations:

extern "C" { // if this matters
typedef struct Rect1 {
  int x, y;
  int w, h;
} Rect1;
}

struct Vector {
  int x;
  int y;
}

struct Rect2 {
  Vector pos;
  Vector size;
}


  • Rect1的 RECT2 对象始终相同?

    具体来说,我可以放心地 reinter pret_cast RECT2 * Rect1的* 并假设在 RECT2 对象全部四个 INT 值匹配一对一的四个 INT S IN Rect1的

    Specifically, can I safely reinterpret_cast from Rect2* to Rect1* and assume that all four int values in the Rect2 object are matched one on one to the four ints in Rect1?

    这是否有所作为,如果我换 RECT2 到非POD类型,例如通过增加一个构造函数?

    Does it make a difference if I change Rect2 to a non-POD type, e.g. by adding a constructor?

    推荐答案


    • 我会这样想,但我也认为有可能(合法)为 RECT2 :: POS之间填充 RECT2 ::大小。因此,要确保,我想补充编译器特定的属性为包的领域,从而保证所有的 INT 是相邻的,紧凑。这是不太关于C与C ++,更多的是,你有可能使用两个不同的编译器在两种语言进行编译时,即使这些编译器来自单一供应商的事实。

    • 使用 reinter pret_cast 的指针转换为一种类型的指针到另一个,你很可能违反严格走样的规则。假设你解引用指针之后,你们会在这种情况下。

    • 添加一个构造函数不会改变布局(虽然它会使类非POD),但添加访问修饰符如私人之间的两个领域可能会改变布局(在实践中,不仅在理论)。

    • I would think so, but I also think there could (legally) be padding between Rect2::pos and Rect2::size. So to make sure, I would add compiler-specific attributes to "pack" the fields, thereby guaranteeing all the ints are adjacent and compact. This is less about C vs. C++ and more about the fact that you are likely using two "different" compilers when compiling in the two languages, even if those compilers come from a single vendor.
    • Using reinterpret_cast to convert a pointer to one type to a pointer to another, you are likely to violate "strict aliasing" rules. Assuming you do dereference the pointer afterward, which you would in this case.
    • Adding a constructor will not change the layout (though it will make the class non-POD), but adding access specifiers like private between the two fields may change the layout (in practice, not only in theory).
    • 这篇关于C / C ++结构体内存布局当量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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