Can you deserialize bytes with memcpy?

混江龙づ霸主 提交于 2019-12-24 09:09:25

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/49990057/can-you-deserialize-bytes-with-memcpy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!