Saving a vector of objects

I have a vector of objects of a class. It is a class with a large number of different types of member variables and functions.

I want to save this vector of objects locally. Given the complexity of the class, saving the vector locally in a file seems unfeasible.

What options do I have to save such a vector locally?
I usually save the number of elements first followed by all the elements. That way I can read the number of elements first to know how many I should read when I'm loading them back into the program.

As for how to store each element depends heavily on what type of object it is. I would recommend making separate functions for saving and loading an object so that the vector saving and loading code can just call those functions.

If the object contains no pointers or references then you essentially just have to make sure to read each member variable in the same order as you wrote them.

If the object contains non-owning pointers or pointers to objects that are shared between multiple objects then it becomes more complicated.
Last edited on
Storing the contents of member variables of a struct/class is called 'serialisation'. It can be complex depending upon the contents of the struct/class. If no dynamic storage is involved (ie just int/double/char - and variants etc) then you can just do a 'shallow' copy. If any involve dynamic memory then the complexity multiplies - especially if you have containers with a type of another container that uses dynamic memory etc.

If you do a search for "C++ serialisation" you'll find plenty of guidance and links to libraries.
As others have said, your problem is mostly about how to write (read) an object to (from) a file.
Having more than one object (in a vector) is just repetition.

a class with a large number of different types of member variables and functions.

Functions are not important. Those are defined in the program.

You can break down the "how to write an object" into "how to write each data member". Those are objects too (of different type).
Topic archived. No new replies allowed.