mercredi 28 octobre 2020

static_assert failed: size of struct is not the same as sum of sizes of all properties [duplicate]

I'm new to C++ languages and I'm writing a data structure which will be used to serialize/deserialize data saved on local machine. The code data structure looks like this:

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");

However, this code failed to compile because the static assert failed with this error:

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    

But I don't quite understand why this is happening. I have one float, two integers, and two time_t in my data structure, so the size of this struct should be the same as "(sizeof(float) + 2 * sizeof(int) + 2 * sizeof(time_t)"

Also, when I changed the static_assert to code below, it somehow worked:

static_assert(sizeof(DerMeasurementData) == (sizeof(float) + 3 * sizeof(int) + 2 * sizeof(time_t))

Can someone please let me know why this is happening?

Best

Aucun commentaire:

Enregistrer un commentaire