Optimizing memory alignment not only in terms of performance, but also in memory size

We know that there is a difference in size Awhen you define Aas follows:

class A 
{
  short a;
  double b;
  short c;
};

or how is it

class A 
{
  short a;
  short c;
  double b;
};

I assume we are compiling a 32-bit OS, and we told the compiler to align to 32 bits.

Does the compiler really reorder the definitions to get the minimum size, while also achieving the same performance?

+4
source share
3 answers

It is very difficult. To arrange the fields in the same sequence as the structure definition, a certain structure is required.

, , , .

. . , , , - CPU.

+4

, ( ): 9.2.12:

() , , . , ,

, :

class A
{
public:
  int a;
  int b;
private:
  int c;
 int d;
{'\;

a b . c d , (a b) wit (c d)

+1

- (: , ++, ).

. , : , , clnflict.

() . , , ; 500 2k .

[edit] , PVS Studio, , .


[edit2] " ":

tl; dr: , , .

( SO) :

, , , , . , , ( , , ) . , .

, reinterpret_cast, ( , , ) . [. , , , , . -end note]

( , C, ++ .)

, " " :

- , .

, , , . ( " " C " " " " )

, :

" " - . ( ). , .

++, : (.. " , , ): ( , ). , () (" "). OTOH , , , secuirty.

0

All Articles