beautypg.com

HP Integrity NonStop J-Series User Manual

Page 176

background image

Example Two: Simple Persistence and Pointers

This example shows one of the shortcomings of simple persistence: its inability to maintain the
pointer relationships among persisted objects. Let's say that you have a class Developer that
contains a pointer to other Developer objects:

Developer {
public:
Developer(const char* name, const Developer* anAlias = 0L)
: name_(name), alias_(anAlias) {}
RWCString name_; // Name of developer.
const Developer* alias_; // Alias points to another Developer.
};

Now let's say that you have another class, Team, that is an array of pointers to Developers:

class Team {
public:
Developer* member_[3];
};

Note that Team::member_ doesn't actually contain Developers, but only pointers to Developers.

We'll assume that you've written overloaded extraction and insertion operators that use simple
persistence to save and restore Developers and Teams. The example code for this is omitted to
keep the explanation from getting cluttered.

When you save and restore a Team with simple persistence, what you restore may be different
from what you saved. Let's look at the following code, which creates a team, then saves and
restores it with simple persistence.

main (){
Developer* kevin = new Developer("Kevin");
Developer* rudi = new Developer("Rudi", kevin);
Team team1;
team1.member_[0] = rudi;
team1.member_[1] = rudi;
team1.member_[2] = kevin;
// Save with simple persistence:
{
RWFile f("team.dat");
f << team1; // Simple persistence of team1.
}
// Restore with simple persistence:
Team team2;
{
RWFile f("team.dat");
f >> team2;
}

This manual is related to the following products: