Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing complex C++ objects to file

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.

like image 920
Anand Avatar asked Feb 26 '26 12:02

Anand


2 Answers

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...

like image 179
ForEveR Avatar answered Mar 01 '26 02:03

ForEveR


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.

like image 34
SingerOfTheFall Avatar answered Mar 01 '26 03:03

SingerOfTheFall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!