0

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

  • `sizeof(int)` happened to be equal to the size of all the padding bytes combined, so your second assert worked. – cigien Oct 29 '20 at 02:34
  • @cigien thank you for your comment. Yes it turned out the padding bytes are the reason why this static_assert is not working. For my purposes, how can I fix this? Is it simply changing the size check to be: (sizeof(float) + 2 * sizeof(int) + 2 * sizeof(time_t) + 4) == sizeof(DerMeasurementData)? What's some down side if I fix it like this? – DarkChocoBar Oct 29 '20 at 02:38
  • Here's a [start](https://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c/), there are some nice answers there :) – cigien Oct 29 '20 at 02:46

0 Answers0