简体   繁体   中英

c++ - struct and class padding

I always pad my structs in C to get the maximum performance (good memory alignment).

// on a x86_64 
struct A {

 int64_t z;
 int32_t x;
 int16_t y;
 // we don't care the uint8_t position, as they are 1 byte wide.
 uint8_t s[8];
 uint8_t t[4];

}

But if I decide to go the c++ route, creating an object for another purpose, I need a class:

class B {

   B(){}
  ~B(){}

 public:
   int64_t a;
   int8_t  b;

 private:
   int32_t c;

//methods...
}

Then, c is not aligned anymore.

Is there a way to avoid doing that (multiple labels):

class B {

  B(){}
  ~B(){}

 public:
   int64_t a;

 private:
   int32_t c;

 public:
   int8_t  b;

}

(on some cpus, alignment matters). Thanks

Yep. Put all the state in a struct, aligned and padded as you wish. Preferably no member functions on the struct, keep it trivial. The class holds a private instance of this struct. Class member functions act on this state directly.

That should suffice. Plus you get a clear separation between state and functions which is always nice. Tends to be used with set/get functions in the class, unless you're especially attached to using inconsistent syntax for function calls and state access.

Alignas may also be of interest.

your effort is complete waste of time. the compiler does the alignment of himself correct (if you not explicitly tell him not to do so). It inserts bytes between members. and it inserts enough bytes at the end of the structure in a way that that its overall size is a multiple of the structures alignment rule.

Your effort is also contra productive. that if compiling for another architecture with other alignment rules? then the compiler inserts padding bytes to your padding bytes.

Explicit alignments and packed structs only matter if data should be exchanged beyond the scope of the compiler or architecture.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM