shuisheng wrote:
Dear All,
Assume I have two classes: material and shape, as follows
class Material
{
double density; // material attribute, may have more
vector<Shape*pShape; // shape objects assocaited the material.
};
class Shape
{
double size; // shape attribute, may have more
vector<Material*pMaterial; // material objects associated with the
shape
};
and I have two objects:
vector<Material*pMaterial;
vector<Shape*pShape;
And I want to save the two objects into a file and then open it by
using fstream. But here pointer is used to represent the association
relation. If I simply save the pointer address in to the file, when
opening there is no gurantee to have those materials and shapes at the
same address. Is there any good way to solve the problem?
There are several solutions to this. Look up information about object
streaming.
The basics is to hold a map of something like:
std::map< void *, int pointers;
As you serialise every time you come across a new pointer you enter it
in the map something like this:
pointers[ p ] = pointers.size();
You then write the number that you have in the map into the file
instead of the pointer.
As you load them from disk you do the reverse:
std::map< int, void * pointers;
You will need to use a placement new to construct the objects and
you'll also need to be able to get the types somehow, some sort of
factory for the objects you stream. There are a number of these sorts
of detail that you need to get straight and they can get quite tricky.
Many years ago (using C++ compilers much worse than those today) I
wrote a Dr. Dobbs article explaining the approach in a bit more detail.
I wouldn't implement it anything like that today with a decent compiler
though, although you should be able to pick up more detail on the
general approach.
http://www.ddj.com/184409645?pgno=3
K