I see a couple of problems. Disadvantage:
*(T*)dest = source;
IIRC, this is UB due to a violation of alias rules ( char * can use any other pointer, but that means you can access some object using the char * pointer, but not vice versa, as in your example).
In other words, will the code be: ... Always return false?
Maybe not, but you mentioned serializing more than just one object.
So the main problem is alignment :
std::unique_ptr<char[]> buffer { new char[sizeof(int) + 1] }; char x = 0; int y = 0; serialize(x, buffer); serialize(y, buffer);
The invalid string is the same (but also deserialize ):
*(T*)dest = source; // source is int, dest is not aligned
The compiler will assume that dest is correctly aligned and uses CPU instructions for aligned storage (on ARM architectures, this will cause real problems).
The solution is to use memcpy instead:
memcpy(dest, &source, sizeof(T));
No need to worry about performance. Modern compilers can very well optimize memcpy objects with known sizes.
source share