Reputation: 1421
If I have a class that has primitives in it, a bunch of ints or chars for example, is it possible to do deserialize and serialize it with memcpy?
MyClass toSerialize;
unsigned char byteDump[sizeof(toSerialize)];
memcpy(&byteDump, &toSerialize, sizeof(toSerialize));
WriteToFile(byteDump);
Then on another program or computer, do this:
MyClass toDeserialize;
unsigned char byteDump[sizeof(toSerialize)];
LoadFile(byteDump);
memcpy(&toDeserialize, &byteDump, sizeof(byteDump));
I have cases where this does in fact work in the same program. But if I try to run it on other programs or PCs, it sometimes does not work and MyClass
will have different values. Is this safe to do or not?
Upvotes: 2
Views: 1111
Reputation: 63922
Is this safe to do or not?
Between different programs or platforms, memcpy
is not safe. You are not assured that the byte layout of a type will be consistent.
Within the same program on the same platform, a well-formed* type T
may be serialized with memcpy
only if is_trivially_copyable_v<T>
is true
.
std::atomic
is a type that takes advantage of certain types being bytewise copyable.
*A type T
is considered "well formed" if there are not bugs in the defined or defaulted constructors, assignment operators, or destructor.
Upvotes: 4
Reputation: 2505
In short, no. memcpy()
was not designed for this. Having said that, you can get away with it if you don't care about cross-platform issues, for both data and executable.
As long as data is stored and retrieved consistently, memcpy()
won't care.
Upvotes: 1