|
Boost : |
From: Li Lirong (lilirong_at_[hidden])
Date: 2002-10-21 23:32:46
Hi,
I'm a user of the serialization library. Since it is not a formal boost
lib yet, I post my quest here instead of the user list.
I found a problem with the serialization library: When a class has
multiple base class, an object of the derived class can not be stored
and loaded through a pointer to the base class that is not the first
base class. The reason is that during the loading and saving procedure,
the base pointer is first casted to a void pointer and then casted back
to the derived class pointer used static_cast. Although the true type
of the object can be determined by the system, but the address of the
derived object get by this way is not correct because the address of the
base class is not the same as the pointer to the derived object. Please
see the attached source code.
Any solution for this problem?
Regards,
Lirong
The following example shows the problem:
struct A
{
virtual ~A() {}
};
struct B
{
virtual ~B() {}
static boost::version_type version(){return 0;}
void save(boost::basic_oarchive &ar) const
{
// empty
}
void load(boost::basic_iarchive &ar, boost::version_type
file_version)
{
// empty
}
};
struct C : A, B // B is the second base class
{
std::string c;
static boost::version_type version(){return 0;}
void save(boost::basic_oarchive &ar) const
{
ar << c;
}
void load(boost::basic_iarchive &ar, boost::version_type
file_version)
{
ar >> c;
}
};
void main()
{
C* pC = new C;
B* pB = pC;
pC->c = "hello";
std::cout << pC->c << std::endl;
// try to save C through pB
std::ofstream ofs("testfile", std::ios::binary);
boost::oarchive oa(ofs);
oa.register_type<C>();
oa << pB;
ofs.close();
delete pB;
// try to load C through pB
std::ifstream ifs("testfile", std::ios::binary);
boost::iarchive ia(ifs);
ia.register_type<C>();
ia >> pB;
ifs.close();
pC = static_cast<C*>(pB);
std::cout << pC->c << std::endl; // failed to print out "hello"
delete pB;
}
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk