beautypg.com

HP Integrity NonStop J-Series User Manual

Page 175

background image

The example uses the overloaded insertion operator operator<< to save the objects, and the
overloaded extraction operator operator>> to restore the objects, much the same way as you use
these operators to output and input objects in C++ streams.

Note that the saving stream and the restoring stream are put into separate blocks. This is so that
opening pi will cause it to be positioned at the beginning of the file.

Here's the code:

#include
#include
#include
main (){
int j1 = 1;
int k1 = 2;
// Save integers to the file "int.dat"
{
// Open the stream to save to:
ofstream f("int.dat");
RWpostream po(f);
// Use overloaded insertion operator
// "RWpostream::operator<<(int)" to save integers:
po << j1;
po << k1;
}
// Restore integers from the file "int.dat"
int j2 = 0;
int k2 = 0;
{
// Open a separate stream to restore from:
ifstream f("int.dat");
RWpistream pi(f);
// Use overloaded extraction operator
// "RWpistream::operator>>(int)" to restore integers:
pi >> j2; // j1 == j2
pi >> k2; // k1 == k2
}
assert(j1 == j2);
assert(k1 == k2);
return 0;
}

The preceding example shows how easy it is to use overloaded operators to implement this level
of persistence. So, what are some of the problems with using simple persistence? As mentioned
above, one problem is that simple persistence will not maintain the pointer relationships among
objects. We'll take a look at this problem in the next example.

This manual is related to the following products: