Search code examples
c++fileserializationboost

C++ serialization of data-structures


I'm studying serializations in C++. What's the advantage/difference of boost::serialization if compared to something like:

ifstream_obj.read(reinterpret_cast<char *>(&obj), sizeof(obj)); // read
// or
ofstream_obj.write(reinterpret_cast<char *>(&obj), sizeof(obj)); // write
// ?

and, which one is better to use?


Solution

  • The big advantages of Boost Serialization are:

    • it actually works for non-trivial (POD) data types (C++ is not C)
    • it allows you to decouple serialization code from archive backend, thereby giving you text, xml, binary serialization
    • If you use the proper archive you can even have portability (try that with your sample). This means you can send on one machine/OS/version and receive on another without problems.

    Lastly, it adds (a) layer(s) of abstraction which make things a lot less error prone. Granted, you could have done the same for your suggested serialization approach without much issue.

    Here's an answer that does the kind of serialization you suggest but safely:

    Note that Boost Serialization is fully aware of bitwise serializable types and you can tell it about your own too: