Is bitfield assignment safe?

I have a bunch of properties hammered into a bitfield to save space:

struct Flags {
    uint access : 2;
    uint status : 2;
    uint isEnabled : 1;
    uint isDeletable: 1;
    ...
};

      

Then I have a static Flags defaultFlags

one that is initialized when the program starts. My main question is, is it safe flags = defaultFlags;

in the object constructor to exclude 20 lines for assigning each field separately?

Also, I was wondering what about serialization? According to the compiler, Flags

is 4 bytes, can I serialize this as an unsigned 32 bit integer and desterilize it as such without any data corruption?

+3


source to share


1 answer


My main question is: are flags safe = defaultFlags; into object constructor to exclude 20 lines to assign each field individually?

Yes. The implicitly defined copy constructor for Flags

will assign each bit to bit appropriately. [Class.copy] / 15:

Each basic or non-static data item is copied / moved in a manner appropriate to its type:

  • if the element is an array, [..]
  • if the member m

    is of an rvalue reference type T && & [..]
  • otherwise the base or element is initialized directly with the corresponding base or member x

    .

Can I serialize this as an unsigned 32-bit integer and distil it as such as data corruption?



If you write and read the file on the same computer with the same compiled program, yes. However, the layout may differ from other compilers or architectures, however the standard does not impose any fixed requirements in this regard. [Class.bit] / 1:

Distribution of bit-fields within an object of an implementation class. Alignment of bit fields of implementation. Bit fields are packed into some addressable allocation unit. [Note. Blocks to allocate blocks of bit-fields to some machines and not others. Bit fields are assigned from right to left on some machines, left to right on others. - end note]

If you write it to an array of char

size sizeof Field

, write that to a file and extract it again, copying it back to an object Field

, you should give you the same values. [basic.types] / 2 (emphasis mine):

For any object (other than a base class subobject), the copy type is trivial T

, regardless of whether the object has a valid type value T

, the base bytes (1.7) that make up the object can be copied into an array char

or unsigned char

. If the content is an array char

or unsigned char

copied back to an object, the object subsequently retains its original value.

However, as pointed out in the comments, full portability (and reasonable efficiency) can be achieved using bitmasks.

+3


source







All Articles