Re: Saving and reloading a container to/from disk
On Mar 31, 7:07 am, jacob navia <ja...@jacob.remcomp.fr> wrote:
Hi
What would be the best way to save and reload later a container
to/from disk in C++?
Thanks
Here's a solution, what constitutes "best" depends on what you
consider important:
If the container contains Plain-Old-Data types or pointers to PODs --
first fread()/fwrite() the size() [if its variable]. After that just
iterate over the elements, and fread() / fwrite() the data,
dereferencing as appropriate as you go. If you've got pointers to
polymorphic types, make sure their base type has a [virtual]
serialize(), and each derived types implementation includes enough
extra header information the first element to determine its type
// Could easily be a static member function...
Base* unserialize()
{
FILE* file_descriptor = fopen("filename","rb");
// read header, determine DerivedType
switch(DerivedType){
case DerivedType1:
return DerivedType1::unserialize(file_descriptor);
case DerivedType2:
return DerivedType2::unserialize(file_descriptor);
/// etc
default:
throw(std::runtime_error("Unrecognised derived type header in
Base* unserialize()"));
}
}
Dumping the vtable / function pointers, even if you can find them, is
a recipe for disaster.