联合中的位字段-这具有多大的可移植性? [英] Bit fields in a union - how portable is this?

查看:109
本文介绍了联合中的位字段-这具有多大的可移植性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一堆标志的位字段,并且我需要一种快速而肮脏的方法将所有内容都设置为零,因此,我不是将结构盲目地转换为整数,而是决定将与实际整数的并集中的位字段.

I got a bit field with a bunch of flags, and I need a quick and dirty way to set everything to zero, so instead of blindly casting the struct to an integer, I decided it would be "better" to put the bit fields in a union with an actual integer.

union Flags {
    uint _all;
    struct {
        uint status : 2;
        uint expanded : 1;
        uint draw : 1;
        uint drawChildren : 1;
        uint hidden : 1;
        uint disabled : 1;
        uint used : 1;
        uint deletable : 1;
        uint incomplete : 1;
        uint isStatic : 1;
        uint isConst : 1;
        uint isVolatile : 1;
        uint isInline : 1;
        uint isMutable : 1;
        uint isExtern : 1;
        uint isRegister : 1;
        uint threadLocal : 1;
        uint packed : 1;
        uint dirty : 1;
        uint native : 1;
        uint dynamic : 1; // 22
        uint _padding : 10;
    } flags;
};

我的问题是,它的便携性如何?我可以期望它使用GCC作为编译器在不同平台(主要对Windows,Linux,macos,android,ios)上具有可移植性吗?

My question is how portable is this? Can I expect it to be portable across different platforms (mostly interested in windows, linux, macos, android, ios) using GCC as a compiler?

或者强制转换为整数并以这种方式设置它并摆脱联合是解决办法?我一直在读,位域不是可移植的,但是例如Qt似乎经常使用它们,并且它在我列出的平台上似乎可以统一工作.

Or maybe casting to an integer and setting it this way and getting rid of the union is the way to go? I keep reading that bit fields are not portable, and yet for example Qt seems to use them quite a lot and it does seem to work uniformly across the platforms I listed.

最后但并非最不重要的一点是,即使没有联合,我也可以期望位字段具有可移植性吗?

Last but not least, even without the union, can I expect the bit fields to be portable?

无法添加C作为标签,但是我也需要在c中使用它,因此我不能使用std::bitset,而且我的成员占用的时间不止一位.

Could not add C as a tag, but I need this to work in C as well, so I can't use std::bitset, also I have a member that takes more than one bit.

还请注意,没有一个成员越过其对齐边界,我认为这会导致编译器不添加额外的填充.

EDIT 2: Also note that none of the members crosses its alignment boundary, which I assume should cause the compiler to not add extra padding.

也许我可以使用GCC的__attribute__(packed)来防止编译器破坏结构?

EDIT 3: Maybe I can use GCC's __attribute__(packed) to prevent the compiler from mangling with the structure?

推荐答案

一旦设置了一个联盟成员,所有其他成员的值都是不确定的,因此从技术上讲,这不符合标准.如果要将所有内容都设置为零,只需使用memset,它完全符合标准,而且通常会被解释为内在函数,并为您提供最大的性能. (而且更简单.)

Once you set one member of a union, the values of all other members are undefined, so this is technically not standards-compliant. If you want to set everything to zero, just use memset, which is entirely standards-compliant and furthermore will generally be interpreted as an intrinsic and give you the maximum possible performance. (And it's simpler.)

这篇关于联合中的位字段-这具有多大的可移植性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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