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. First, you have a struct Developer that contains a pointer to other Developer objects:
struct Developer
{
explicit
Developer(const char* name, const Developer* anAlias = 0L)
: name_(name), alias_(anAlias) { }
RWCString name_;
const Developer* alias_;
};
Now, you have another struct, Team, that is an array of pointers to Developer s:
struct Team
{
Developer* member_[3];
};
Note that Team::member_ does not actually contain Developers, but only pointers to Developers.
Assume that you have 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 clear.
When you save and restore a Team with simple persistence, what you restore may be different from what you saved. Look at the following code, which creates a team, then saves and restores it with simple persistence.
int 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;
}
return 0;
}
Because this example uses simple persistence, which does not maintain pointer relationships, the restored
team has different pointer relationships than the original
team.
Figure 1 shows what the created and restored
teams look like in memory if you run the program.
Figure 3 shows that when objects that refer to each other are saved and then are restored with simple persistence, the morphology among the objects can change. This is because simple persistence assumes that every pointer reference to an object in memory refers to a unique object. Thus, when such objects are saved, two references to the same memory location will cause two copies of the contents of that memory location to be saved, and later restored.