结构前缀的布局 [英] Layout for struct prefix

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

问题描述

C / C ++语言不会在内存中对结构成员进行重新排序,并且永远不会在第一个成员之前插入填充。但是,如果我有两个以相同成员开头的结构,如果我仅访问公共成员,是否可以在它们之间进行转换?换句话说,结构布局是贪婪的吗?我的具体案例是在 VIDEOINFOHEADER之间进行转换 VIDEOINFOHEADER2

The C/C++ languages don't reorder struct members in memory and never insert padding before the first member. But if I have 2 structures that start with the same members, can I cast between them if I only access the common members? In other words, is struct layout greedy? My concrete case is casting between VIDEOINFOHEADER and VIDEOINFOHEADER2

推荐答案

C ++标准包含以下语句,但该语句仅适用于联合(9.2 [class.member]第19段):

The C++ standard contains the following statement which, however, only applies to unions (9.2 [class.member] paragraph 19):


如果标准布局联合包含两个或多个共享公共初始序列的标准布局结构,并且标准布局联合对象当前包含这些标准布局结构之一,允许检查其中任何一个的公共初始部分。如果相应的成员具有与布局兼容的类型,并且对于一个或多个初始成员的序列,两个成员都不是位域,或者两者都不是具有相同宽度的位域,则两个标准布局结构共享一个公共的初始序列。

If a standard-layout union contains two or more standard-layout structs that share a common initial sequence, and if the standard-layout union object currently contains one of these standard-layout structs, it is permitted to inspect the common initial part of any of them. Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.

对于C或C ++标准中的部分定义的结构,我没有看到任何其他保证。不过,这并不意味着它不存在,只是我没有通过快速浏览几个相关部分来找到它。

I didn't see any other guarantee with respect to partially defined structures in either the C or the C++ standard. That doesn't mean it isn't there, though, just that I haven't found it with a quick scan of a couple of relevant sections.

这篇关于结构前缀的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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