Adjacent Class Data

I have a C ++ class that has four private floats and a bunch of non-static public functions that work with this data.

Whether it is guaranteed or it is possible to ensure that the four floats are adjacent and there is no gasket. This would make the class four floats in size, and its address would be the address of the first float.

+4
source share
3 answers

It depends on your compiler.

You can use #pragma pack(1) for example. MSVC and gcc or #pragma pack 1 with aCC .

For example, assuming MSVC / gcc :

 #pragma pack(1) class FourFloats { float f1, f2, f3, f4; }; 

Or better:

 #pragma pack(push, 1) class FourFloats { float f1, f2, f3, f4; }; #pragma pack(pop) 

This basically disables padding and ensures that floats are contiguous. However, to ensure that the size of your class is actually 4 * sizeof(float) , it should not have vtbl , which means virtual members are limits.

+7
source

The C ++ standard ensures that arrays are stored contiguously, without intermediate filling. If you want to make sure the floats are contiguous, and you don't want to rely on compiler-specific add-on directives, you can simply store your floats in an array:

 private: float array_[4]; 

However, this does not necessarily guarantee that the class will be the size of four floats. But you can make sure that any operation that is specifically addressed to the internal array of floats will work in a continuous array.

But in general, maybe you should ask a question why you need this guarantee. Typically, the only reason you need a class memory layout is to treat it as a serialized byte array. In this case, it is usually better to create a special serialization / deserialization function, rather than relying on any specific memory layout.

+8
source

You can use the #pragma pack description here and here for this.

+3
source

All Articles