2

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?

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
alexj123
  • 33
  • 3

1 Answers1

1

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:

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Are you referring with this advantages to my examples(write,read) in the question?... – alexj123 Jan 25 '16 at 19:01
  • @alexj123 What else? – sehe Jan 25 '16 at 19:02
  • actually you are talking about `boost::serialization`, aren't you? I thought my examples were valid for "little" projects(for programs which don't do nothing of particular). – alexj123 Jan 25 '16 at 19:13
  • 1
    Me too. Also, this answers your question: _"I'm studying serializations in C++. What's the advantage/difference of boost::serialization if compared to something like: [...]"_. There are cases where you *might* get away with what you had, but be sure to do it safely (see the first linked answer) – sehe Jan 25 '16 at 19:15