N
nw
Hi,
I have some simple objects I wish to serialize and I'm wondering
what's wrong with the following naive approach. The objects will never
contain pointers or references to other objects, they are simple
containers of primitive types.
The serialization method I'm using simply takes the base pointer of
the object, then dump the memory from base pointer to base pointer +
sizeof(object). To deserialize the object the dumped representation is
written over the memory space of a newly instantiated object.
So, I can understand this isn't a great idea. But is it outside the
standard? Is the memory layout of a class guaranteed to stay the same
(during execution)?
Example serialization method (writes serialized representation to
storage_area), in my implementation object_type is a template
parameter:
void set(size_t index,const object_type &o) {
size_t write_end_position = (index+2)*(object_size);
for(size_t n=0;n<object_size;n++) {
storage_area[(index*object_size)+n] = ((const char *)(&o))[n];
}
}
Example deserialization method (reads from storage_area):
object_type get(size_t index) {
object_type o;
for(size_t n=0;n<object_size;n++) {
((char *)(&o))[n] = storage_area[(index*object_size)+n];
}
return o;
}
I have some simple objects I wish to serialize and I'm wondering
what's wrong with the following naive approach. The objects will never
contain pointers or references to other objects, they are simple
containers of primitive types.
The serialization method I'm using simply takes the base pointer of
the object, then dump the memory from base pointer to base pointer +
sizeof(object). To deserialize the object the dumped representation is
written over the memory space of a newly instantiated object.
So, I can understand this isn't a great idea. But is it outside the
standard? Is the memory layout of a class guaranteed to stay the same
(during execution)?
Example serialization method (writes serialized representation to
storage_area), in my implementation object_type is a template
parameter:
void set(size_t index,const object_type &o) {
size_t write_end_position = (index+2)*(object_size);
for(size_t n=0;n<object_size;n++) {
storage_area[(index*object_size)+n] = ((const char *)(&o))[n];
}
}
Example deserialization method (reads from storage_area):
object_type get(size_t index) {
object_type o;
for(size_t n=0;n<object_size;n++) {
((char *)(&o))[n] = storage_area[(index*object_size)+n];
}
return o;
}