C / C ++结构体内存布局当量 [英] C/C++ Struct memory layout equivalency
本文介绍了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 INRect1的
?Specifically, can I safely
reinterpret_cast
fromRect2*
toRect1*
and assume that all fourint
values in theRect2
object are matched one on one to the fourint
s inRect1
?这是否有所作为,如果我换
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
andRect2::size
. So to make sure, I would add compiler-specific attributes to "pack" the fields, thereby guaranteeing all theint
s 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屋!
- 我会这样想,但我也认为有可能(合法)为
查看全文