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.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With