您可以使用memcpy反序列化字节吗? [英] Can you deserialize bytes with memcpy?
问题描述
如果我有一个带有原始类型的类,例如一堆int或char,是否可以使用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));
在某些情况下,这实际上在同一程序中起作用.但是,如果我尝试在其他程序或PC上运行它,它有时将不起作用,并且MyClass
将具有不同的值.这样安全吗?
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?
在不同的程序或平台之间,memcpy
是不安全的.您不能保证类型的字节布局会保持一致.
Between different programs or platforms, memcpy
is not safe. You are not assured that the byte layout of a type will be consistent.
在同一平台上的同一程序中,只有当 is_trivially_copyable_v<T>
为true
时,格式良好的*类型T
才可以使用memcpy
进行序列化.
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
是一种利用某些可按字节复制的类型的类型.
std::atomic
is a type that takes advantage of certain types being bytewise copyable.
*如果已定义或默认的构造函数,赋值运算符或析构函数中没有错误,则类型T
被视为格式正确".
*A type T
is considered "well formed" if there are not bugs in the defined or defaulted constructors, assignment operators, or destructor.
这篇关于您可以使用memcpy反序列化字节吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!