views:

249

answers:

4

Is there something similar to Java/.NET serialization for C++?

+6  A: 

Boost contains a serialization library. I haven't used it myself, but usually the boost libraries work quite well.

sth
while you answer the question in the body, you didn't address the question in the title - which is the more interesting one
Idan K
+4  A: 

Unfortunately there is no automatic way to serialize objects in C++. That is because any serialization engine needs to be able to "understand" your custom made object in the run-time and C++ doesn't contain the necessary information for that. Java and .Net on the other side have, what is called, Reflection. This mechanism allows anyone to browse the data structure of any arbitrary object in the run-time.

All this doesn't mean that there is no way to serialize a C++ object with a relatively little effort. Take for example the standard C++ streams library. By writing

int x = 2010;
cout << x << endl;

you actually serialize an object of type int. It is possible to extend this mechanism to support your custom class too. This is done just by overloading operator<<. It isn't as nice as Java serialization, but it is very convenient too.

There are also some libraries that make it even more simple. As someone already mentioned, boost serialization library does a good job. Working with boost serialization looks very similar to working with iostream but it solves some problems inherent to the standard streams.

FireAphis
+1  A: 

Google's protocol buffers provides a C++ implementation in the core package; as a nice benefit, you can then share this data with lots of other languages - but you will be limited to using the generated types rather than your own (which some serialization engines in other languages support).

In reality this isn't a problem, as (if necessary) you can just treat the generated types as a DTO that twin to your actual domain objects.

Marc Gravell
+1  A: 

Boost.Serialization is a very good library and it also supports basic versioning - something that is never quite possible with automatic serialization. Because I happened to need even better versioning, I actually wrote my own serialization library that follows the Boost.Serialization style (because the author of Boost.Serialization was not interested on improving it).

Notice that you can also abuse the serialization functions for other purposes such as GUI or web form generation, if a little bit of helper data is added (see how Boost.Serialization does XML).

It needs to be noted that the popular method of saving entire structs (by casting them to char* and writing sizeof(struct) bytes) is completely unportable, it doesn't support versioning and it breaks if the struct contains any pointers or C++ (non-POD) objects.

Tronic