c++通用 to_stream() 和 from_stream()
我想知道以下是否有效(我猜不是,否则每个人都会使用它,对吧?:-))。我在我编写的简单类上尝试了它们,但我想知道它是否适用于一般情况。只需将对象的内存复制到 CHAR[]
即可为泛型类编写一个 to_stream()
函数吗?
例如:
memcpy(buf, (void*)&object1, sizeof(object1))
现在,我可以通过简单地将内存从 CHAR[]
复制到对象来为泛型类编写一个 from_stream()
函数吗?
例如:
memcpy(&object2, buf, buf_len) // or using sizeof(C) instead of buf_len.
ps 我不会在实际产品中使用此代码,这只是一个更好地理解内部结构的问题。 谢谢 :-)
I wonder if the following works (I guess not, otherwise everyone would've used it, right? :-)). I tried them on simply classes I wrote, but I wonder if it works for the general case. One can write a to_stream()
function for a generic class by simply copying the memory of the object to CHAR[]
?
For instance:
memcpy(buf, (void*)&object1, sizeof(object1))
Now, can i write a from_stream()
function for a generic class by simply copying the memory from CHAR[]
to the object?
For instance:
memcpy(&object2, buf, buf_len) // or using sizeof(C) instead of buf_len.
p.s.
I AM NOT going to use this code in an actual product, this is simply a question to understand better the internals.
Thanks :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如这个问题的回答所述,您将对象视为原始字节没有任何好处。这适用于聚合类型/POD 类型,但如果您在该类中只有一个虚函数或指针/引用,那么您就完蛋了。
As explained in an answer to this question, you will do no good in treating objects as if they were raw bytes. This will work for aggregate types / POD types, but if you got but a virtual function or a pointer/reference in that class, you're f*cked.
不,这是可怕的未定义行为。永远不要尝试。复制构造函数之类的东西的存在是有原因的。
No, this is hideously undefined behaviour. Don't ever try it. Copy constructors and that kind of thing exist for a reason.
您要做的就是实现序列化。但您所做的方式不适用于具有其他引用或指针的通用对象。您将复制它们在内存上的位置(仅它们的指针地址),这不是您的意图。当对象被“反序列化”并且内存被释放或被其他对象占用时,这可能会崩溃并且肯定会产生奇怪的结果。所以不要这样做。
What you're trying to do is to implement serialization. The way that you're doing though won't work for generic objects that have other references or pointers. You'll copy their location on memory (their pointer address only), which is not your intention. This will probably crash and certainly give strange results when the object is "deserialized" and the memory is freed or occupied by other objects. So don't do it.
不要像这样“序列化”对象。你会弄错并违反标准。
相反,让你的对象变得智能,这样你就可以以某种合理的方式序列化它们。也许看看 Boost.Serialize。
它可能在某些情况下“有效”(例如,当与没有虚拟成员的 POD 类型一起工作时,存储的间接或其他奇特的语义),但它是:
这就是人们不这样做的原因。
Don't "serialise" objects like this. You will get it wrong and violate the standard.
Instead, make your objects intelligent such that you can serialise them in some sensible manner. Perhaps look at Boost.Serialize.
It may "work" in some situations (for example, when working with POD types who don't have virtual members, stored indirection or other fancy semantics), but it's:
That's why people don't do it.