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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With