Re: Easiest way to store and save objects generated by a C++ program ?

From: Thomas Matthews (Thomas_MatthewsHatesSpam_at_sbcglobal.net)
Date: 10/28/03


Date: Tue, 28 Oct 2003 15:50:24 GMT

Rolf Hemmerling wrote:

> Hello !
>
> Beginner's question:
>
> What ist the easiest way to store and save objects in a file generated
> by a C++ program, by using the "standard C++ library" and/or "Standard
> Template Library ( STL )" ?
>
> So I would like to generate some objects ( of different classes ) with a
> C++ program and would like to make it permanent / persistent, so that
> when calling the C++ program next time, I can load the objects from that
> file and use it again ( or use the data stored in that objects )?
>
> I dont´want to store text data in text files, with non-trivial methods
> to save and restore the data. So I don´t want a data delimiter format.
[snip]

The easiest method is to have binary read and write methods for each
class. These methods would operate on each member individually.
For composite classes, they would call the binary read or write
member for each member.

Be aware that pointers do not serialize (or store permanently)
since there is no guarantee that 1) the program is loaded into
the same address space and 2) that your dynamic memory allocation
is the same for each execution.

For variable records, such as text, I recommend writing the
length out first, then the data.

>
> Sincerely
> Rolf

For a more complex system (and maybe more efficient), each
class should have a method that writes to a buffer, reads
from a buffer and reports the number of bytes it occupies
in a stream. A non-member function binary write function
can sum up the sizes, then allocate a buffer and have
all the objects write to the buffer. The buffer is then
written as one chunk and deleted.

-- 
Thomas Matthews
C++ newsgroup welcome message:
          http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq:   http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
          http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
     http://www.josuttis.com  -- C++ STL Library book


Relevant Pages