Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 625
Kroma Avatar asked Sep 05 '25 03:09

Kroma


1 Answers

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.

like image 122
Jon Chesterfield Avatar answered Sep 07 '25 20:09

Jon Chesterfield