c++ how to serialize/deserialize an object? [duplicate]
Possible Duplicate:
How to save c++ object into a xml file and restore back?
hi,
Can someone tell me what is the best way to seralialize and deserialize (of course) an object? I have a class with a a lot of string, int values. What is the west way to create an XML and after 开发者_运维百科that (when i have the xml) to open it and obtain the values?
Can you give me please code examples?To serialize/deserialize an object, you only have to do this:
ofstream f( "output.bin", ios::binary );
f.write( (char *) &myObject, sizeof( myObject ) );
f.close();
// later...
ifstream f( "output.bin", ios::binary );
MyClass myObject;
f.read( (char *) &myObject, sizeof( myObject ) );
f.close();
However, this has a lot of drawbacks. For example, your application won't work with object serialized in computer of different architectures. Another big problem is that your objects cannot have any relationship with other objects, i.e., they must be simple objects.
That's why people use a format much more understandable among different architectures. Text with structure, XML. You can use a number of XML libraries, such as Xerces.
There are various strategies, but from a very simplistic strategy you could even write your own toXML() method in each class you want to be persistent, along with its corresponding [static] fromXML(), and use your own XML parser.
Of course, it would be quite better to use a library like Xerces and conform to its needs.
As you can see, all these insights are beyond the possiblities of an answer here.
You'll have to read about XML, then about Xerces (or other XML parser), and then figure out how to apply this to your application. As you can see, it is a broad topic.
You should check boost.serialization.
精彩评论