Search code examples
c++serializationmarshallingdeserializationunmarshalling

Serializing C++ objects


I would like to implement a Serialization Class which takes in an object and converts it into a binary stream and stored in a file. Later, the object should be reconstructed from a file.

Though this functionality is provided by BinaryFormatter in C#, I would like to design my own Serialization class from scratch.

Can someone point to some resources ?

Thanks in advance


Solution

  • I have been using boost::serialization library for a while now and I think it is very good. You just need to create the serialization code like this:

    class X {
      private:
        std::string value_;
      public:
        template void serialize(Archive &ar, const unsigned int version) {
           ar & value_;
         };
     }
    

    No need to create the de-serialization code ( that's why they used the & operator ). But if you prefer you can still use the << and >> operators.

    Also it's possible to write the serialization method for a class with no modification ( ex.: if you need to serialize an object that comes from a library ). In this case, you should do something like:

    namespace boost { namespace serialization {
           template
           void serialize(Archive &ar, X &x const unsigned int version) {
                        ar & x.getValue();
           };
        }}