C++ serialize giude

来源:互联网 发布:金山软件2017校园招聘 编辑:程序博客网 时间:2024/06/04 01:12

A practical guide to C++ serialization

原网址:http://www.ocoudert.com/blog/2011/07/09/a-practical-guide-to-c-serialization/
In a nutshell, serialization consists of writing data and objects on a support (a file, a buffer, a socket), so that they can be reconstructed later in the memory of the same or another computing host. The reconstruction process is also known as deserialization.

Serializing a primitive type like a bool, int, or float, is trivial: just write the data as it is (assuming that no compression is used). Serializing a pointer is different: the object it points to must be serialized first. That way deserializing the pointer simply consists of setting its value to the memory address at which the object has been reconstructed.

We can distinguish three levels of complexity in serialization, depending on how complex the pointer (and reference) graph is:

  1. The pointer graph is a forest (i.e., a set of trees). Data can simply be serialized bottom up with a depth first traversal of the trees.
  2. The pointer graph is a directed acyclic graph (DAG), i.e., a graph without loop. We can still serialize the data bottom up, making sure we write and restore shared data only once.
  3. The pointer graph is a general graph, i.e., it may have loops. We need to write and restore data with forward references so that loops are handled properly.
The text and XML archives are portable across 32 and 64 bits platforms.

Having a binary archive that is portable between 32 and 64 bits is not trivial, because C++ does not specify exactly the size of primitive types. For instance a long is usually 4 bytes on a 32 bits machine, and 8 bytes on a 64 bits machine. In practice though it is pretty portable –there is a non-official version for a portable binary archive.

原创粉丝点击