简体   繁体   中英

Can you deserialize bytes with memcpy?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM