开发者

Class contiguous data

I have a C++ class which has four private floats and a bunch of nonstatic public functions that operate on this data.

Is it guaranteed, or possible to make it so, that the four floats are contiguous and there is no padding. This would make the class the size of four floats, and it's address wo开发者_如何学Culd be that of the first float.


That depends on your compiler.

You can use #pragma pack(1) with e.g. 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)

That basically disables padding and guarantees that the floats are contiguous. However, to ensure that the size of your class is actually 4 * sizeof(float), it must not have a vtbl, which means virtual members are off-limits.


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

private:
float array_[4];

However, this won't guarantee necessarily that the class will be the size of four floats. But you can ensure that any operation which specifically addresses the internal array of floats will be operating on a contiguous array.

But more generally, maybe you should question why you need this guarantee. Usually, the only reason you'd care about the memory layout of the class is if you're going to treat it as a serialized byte array. In that case, it's usually better to create a dedicated serialization/deserialization function, rather than relying on any particular memory layout.


You can use #pragma pack described here and here for this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜