How to ensure an element matches 4 bytes?

To use OSAtomicDecrement (atom-specific atomic operation), I need to provide a 4-byte aligned SInt32.

Does this type of cooking work? Is there any other way to solve alignment problems?

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

  SInt32 *member_;

  struct {
    SInt32 a;
    SInt32 b;
  } storage_;
};
+3
source share
6 answers

If you are on a Mac, it means GCC. GCC can automatically align variables for you:

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

Please note that this is not portable for compilers, as it is specific to GCC.

+5
source

I would suggest that any SInt32 is already aligned, even on a Mac.

To clarify:

struct Foo {
    SInt32 member;
};

member , char.

+4

int 4 OS X. , , - (, , packed ..).

+1

Mac, , , 4- () . IIRC, . .

0

TR1 ( ++ 0x), std::aligned_storage.

S A, std::aligned_storage<S, A>::storage.

( . , TR1 , . MSVC std::tr1)

, 32- 4- ( , , 32- ints 4 )

0

, .

struct 
{
   Foo _hisFoo;
   unsigned int dummyAlignment : 0;
   Foo _myFoo;
}
-1

Source: https://habr.com/ru/post/1729717/


All Articles