Filling Massive Structures

For a structure containing a sequence of the same basic types, for example:

struct Vector { float x; float y; float z; }; 

Can it contain between members? I was given a link to [class.mem] , which states that an add-on can be added to achieve alignment, but is it applicable in this case?

+5
source share
1 answer

It seems that there are no technical reasons why floats in the structure should be aligned differently than in the array. But still there is no standardization of C ++ at the binary level.

If you want to be safe, you can add static_assert :

 static_assert(offsetof(Vector, y) - offsetof(Vector, x) == sizeof(float)); static_assert(offsetof(Vector, z) - offsetof(Vector, y) == sizeof(float)); 

In addition, you can also disable padding using a non-cross-platform method. For Visual Studio you need #pragma pack and for gcc, you need to use the packed attribute.

+1
source

All Articles