我是 C++ 语言的新手,我正在编写一个数据结构,用于序列化/反序列化保存在本地机器上的数据。代码数据结构如下所示:
struct DerMeasurementData
{
float DerAnalogMeasValue = 0.0;
int DerStatusMeasValue = 0;
int DerMeasQuality = 0;
time_t DerReadingTime = 0;
time_t DerLastUpdateTime = 0;
};
// Ensure that comparison using memcmp will work correctly (currently there is 1 double value, 2 integer value, 2 time_t values in DerMeasurementData struct)
static_assert(sizeof(DerMeasurementData) == (sizeof(float) + 2 * sizeof(int) + 2 * sizeof(time_t)), "sizeof(DerMeasurementData) should be equal to summary size of it's fields");
但是,此代码无法编译,因为静态断言失败并出现以下错误:
Error (active) E1574 static assertion failed with "sizeof(DerMeasurementData)
should be equal to summary size of it's fields" dnom D:\ETD_Repo\IDMS_Dev\dmsSource\portable\serialization\MappedSerializationNew.h 2571
但我不太明白为什么会这样。我的数据结构中有一个浮点数、两个整数和两个 time_t,所以这个结构的大小应该与“(sizeof(float) + 2 * sizeof(int) + 2 * sizeof(time_t)”相同
此外,当我将 static_assert 更改为下面的代码时,它以某种方式起作用:
static_assert(sizeof(DerMeasurementData) == (sizeof(float) + 3 * sizeof(int) + 2 * sizeof(time_t))
有人可以让我知道为什么会这样吗?
最好的