0

In the legacy code, I found many struct are sent or received through system V message queue without any serialization or deserialization. The data member of a struct might be also a struct. The depth can be three. But all the data members of these struct are types of int, float, char or their corresponding arrays. A typical snippet is like this:

A a;  //A is a struct or a struct with struct data members.
....  //initialize a
msgsnd(msgid, &a, sizeof(A), IPC_NOWAIT);

Initially, I thought the serialization is needed. However, I changed my mind later. Although there are paddings for alignment of data members in struct, sending a struct like this without serialization won't cause any problem. Because there are no pointer data members. Through my simple testing, I didn't see any problem. Can anybody confirm that serialization is not needed in this circumstance? Thanks!

tadman
  • 208,517
  • 23
  • 234
  • 262
Wqh
  • 75
  • 1
  • 10

1 Answers1

2

Can anybody confirm that serialization is not needed in this circumstance?

If your struct does not contain pointers, then an additional check can be done by issuing the following:

#include <type_traits>
//...
struct A 
{
  //... stuff
};

void some_function()
{
   static_assert(std::is_trivially_copyable<A>(), "The A struct must be serialized and is not trivially-copyable");
}

This will stop the compilation if the compiler detects that A is not trivially-copyable. This also prevents any future changes to A from breaking your code.

If you were to add a pointer member to the struct, then the compile-time check becomes trickier. Then it would come down to visual inspection, or possibly using magic_get, as mentioned in this answer.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45