c++ generic to_stream() and from_stream()
I wonder if the following works (I guess not, otherwise everyone would've used it, righ开发者_运维知识库t? :-)). 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 :-)
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.
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.
I wonder if the following works (I guess not, otherwise everyone would've used it, right? :-))
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:
- ghastly;
- probably invoking Undefined Behaviour.
That's why people don't do it.
精彩评论