doron doron - 2 months ago 5x
C++ Question

Type Traits of trivially serializable C++ classes

I have a C++ class defined as

A a;
which I would like to serialize. The simplest way to do this (when it works) is

write(fd, reinterpret_cast<uint8_t*>(&a), sizeof(a));

and to read it back using:

read(fd, reinterpret_cast<uint8_t*>(&a), sizeof(a));

I know that this will work if
is true types but what is the most relaxed set of type traits
must exibit for this to to work?

Just for completeness, this is for persistence between running instances of the application, there is no need for the file to be readable by another program or on another platform.


Writing the bitwise image of an object into a stream and restoring it correctly by reading from that stream is exactly the same as the object behaving correctly under memcpy. And for that, there's the specific property of begin trivially copyable. So the trait you want to use is std::is_trivially_copyable<A>.

Unrelated side note: Your code could theoretically have Undefined Behaviour. That is because C++ only allows aliasing through types char and unsigned char, and there's no guarantee that std::uint8_t is an alias for one of those. You'd better off using unsigned char explicitly:

write(fd, reinterpret_cast<unsigned char*>(&a), sizeof(a));