2

I have a C++ objects that looks like this

class myClass
{
    vector<OtherClass*> otherClassVector;
    AnotherClass* anotherClassObj;
    // A few other primitive types and functions
}

What is the best way to store this to disk and read it back programmatically? Will using fstream read/write in binary mode work? Or should I use boost serialization? And why? I don't require the stored file to be human readable.

Anand
  • 7,654
  • 9
  • 46
  • 60
  • look into this http://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c – Jeeva Jul 31 '12 at 07:29
  • 1
    fstream read/write in binary mode will work, as long as you don't think that you can write the whole object out in one go. You will have to write the code yourself to write each individual subobject plus vector sizes and everything else. It's to avoid this kind of tedious and error prone work that you should think about using boost. – jahhaj Jul 31 '12 at 07:30

3 Answers3

6

Using boost::serialization is simply, than write your own serializer. If OtherClass is concrete type (not base) - serialize by read/write is simple, for vector - just save size and than array (if your myClass has no non-POD types) and then store element on which points anotheClassObj pointer...

ForEveR
  • 55,233
  • 2
  • 119
  • 133
3

You can serialize objects with ofstream f("filename", std::ios::binary); only if those objects are POD-types.

Anything else needs to be handled manually. For a simple example, if the object contains any pointers, the addresses of those will be saved, not the data they point at.

For more complex types, you will have to either serialize them completely manually (write a class or function that will save all the POD data from the class and do something tricky with all the "special" data)), or use boost serialization.

KeyC0de
  • 4,728
  • 8
  • 44
  • 68
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
0

The C++_Middleware Writer may be of interest. It has some advantages over other approaches.

Isaiah
  • 1