Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

c++ - 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 would be that of the first float.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...