Why serialization when a class object in memory is already binary (C / C ++)?

I assume that the data is scattered in physical memory (even the data of a class object is sequential in virtual memory), so in order to send data correctly, you need to collect it, and so that it can send networks, another step is to convert the host byte order to byte order network. Is it correct?

+7
source share
5 answers

Proper serialization can be used to send data to arbitrary systems that may not work in the same architecture as the original host.


Even an object consisting only of native types can be an unpleasant sharing of two systems due to the additional complement that can exist between and after members, by the way. Sharing raw dumps of object memory between programs compiled for the same architecture but with different versions of the compiler can also be a big problem. There is no guarantee that the type of the variable T is actually stored in memory.


If you do not work with pointers (links are included), and the data is intended to be read by the same binary code from which it is flushed, it is usually safe only to unload the raw structure to disk, but when sending data to another host .. drum roll serialization is the way to go.

I heard that the developers talked about ntohl / htonl / ntohl / ntohs as methods for serializing / deserializing integers, and when you think about it, saying that it is not so far from the truth.


The word "serialization" is often used to describe this "complex method of storing data in a general way", but again; your first programming assignment, in which you were asked to save information about dogs to a file (hopefully * ), somehow used serialization.

* "hope", which means that you did not unload the original memory representation of your Dog object to disk

+10
source

Pointers

If you allocated memory on the heap, you just get a serialized pointer pointing to an arbitrary memory area. If you have only a few ints and chars , then yes, you can just write it directly to the file, but then it becomes platform dependent due to the byte order you mentioned.

+7
source

Pointer and data packet (data alignment)

If you memcpy your object memory, there is a danger of copying the value of the wild pointer instead of data. There is another risk if the sender and the receiver have a different data collection method, after decoding you will get garbage.

+2
source

Binary representations can be different between different architectures, compilers, and even different versions of the same compiler. There is no guarantee that system A will see as a signed integer, will be considered the same in system B. Byte order, words langths, struct padding, etc. It will be difficult to debug problems if you incorrectly define the protocol or file format for data exchange.

+1
source

The class (when we talk about C ++) also includes pointers to virtual methods - and they need to be restored on the receiving side.

0
source

All Articles