views:

2446

answers:

4

Using java for 3 years and serialization / deserialization is something trivial. I would like to know whether c + + is also well?

It is possible to serialize / deserialize a class in c + +?

If someone can leave me an example would be a great help to me.

EDIT :

There are some native library that allows this?

+16  A: 

The Boost::serialization library handles this rather elegantly. I've used it in several projects.

EDIT 1: There's an example program, showing how to use it, here.

EDIT 2: The only native way to do it is to use streams. That's essentially all the Boost::serialization library does, it extends the stream method by setting up a framework to write objects to a text-like format and read them from the same format. For built-in types, or your own types with operator<< and operator>> properly defined, that's fairly simple; see the C++ FAQ Lite for more information.

Head Geek
+5  A: 

Boost is a good suggestion. But if you would like to roll your own, it's not so hard.

Basically you just need a way to build up a graph of objects and then output them to some structured storage format (JSON, XML, YAML, whatever). Building up the graph is as simple as utilizing a marking recursive decent object algorithm and then outputting all the marked objects.

I wrote an article describing a rudimentary (but still powerful) serialization system. You may find it interesting: Using SQLite as an On-disk File Format, Part 2.

Frank Krueger
Link is broken.
topright
A: 

As far as "built-in" libraries go, the << and >> have been reserved specifically for serialization.

You should override << to output your object to some serialization context (usually an iostream) and >> to read data back from that context. Each object is responsible for outputting its aggregated child objects.

This method works fine so long as your object graph contains no cycles.

If it does, then you will have to use a library to deal with those cycles.

Frank Krueger
+2  A: 

I recommend Google protocol buffers. I had the chance to test drive the library on a new project and it's remarkably easy to use. The library is heavily optimized for performance.

Protobuf is different than other serialization solutions mentioned here in the sense that it does not serialize your objects, but rather generates code for objects that are serialization according to your specification.

yoav.aviram