Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure a member is 4-byte aligned?

In order to use OSAtomicDecrement (mac-specific atomic operation), I need to provide a 4-byte aligned SInt32.

Does this kind of cooking work ? Is there another way to deal with alignment issues ?

struct SomeClass {
  SomeClass() {
    member_  = &storage_ + ((4 - (&storage_ % 4)) % 4);
    *member_ = 0;
  }

  SInt32 *member_;

  struct {
    SInt32 a;
    SInt32 b;
  } storage_;
};
like image 466
Anna B Avatar asked Jan 23 '23 16:01

Anna B


1 Answers

If you're on a Mac, that means GCC. GCC can auto align variables for you:

  __attribute__((__aligned__(4))) int32_t member_;

Please note that this is not portable across compilers, as this is GCC specific.

like image 113
LiraNuna Avatar answered Feb 04 '23 00:02

LiraNuna