I have a bunch of properties crammed in a bitfield to save on space:
struct Flags {
uint access : 2;
uint status : 2;
uint isEnabled : 1;
uint isDeletable: 1;
...
};
Then I have a static Flags defaultFlags
which is initialized on program startup. My main question is whether it is safe to flags = defaultFlags;
in the object constructor, in order to eliminate the 20 lines for assigning each field individually?
Also, I was wondering what about serialization? According to the compiler, Flags
is 4 bytes, can I serialize that as a 32bit unsigned integer and desterilize it as such without any data corruption?
Yes. The implicitly defined copy constructor for
Flags
will assign each Bitfield appropriately. [class.copy]/15:If you write and read the file on the same machine with the same compiled program, yes. The layout might be different on other compilers or architectures though, the standard doesn't impose any fixed requirements in that respect. [class.bit]/1:
If you write it into a
char
array of sizesizeof Field
, write that into a file and extract it from there again, copying it back into aField
object should thus give you the same values. [basic.types]/2 (emphasis mine):However, as pointed out in the comments, full portability (and reasonable efficiency) can be achieved using bitmasks.