I have seen many questions, tutorials, and documentation involving serializing derived classes, and I haven\'t been able to reach a consensus on several issues, including (a
boost::serialization::base_object
vs BOOST_SERIALIZATION_BASE_OBJECT_NVP
The NVP wrapper is only ever required for archives that have element naming, like XML.
Unless you use it, base_object<>
is cleaner and simpler.
archive & mData;
vs archive & BOOST_SERIALIZATION_NVP(mData);
Ditto
BOOST_SERIALIZATION_ASSUME_ABSTRACT(AbstractPoint);
I assume it will merely be an optimization - suppressing registered type information with each archive type, since you told the framework it will never be de-serializing instances of the type
serialize()
for a class in the hierarchy that doesn't need to serialize anything.You don't need it, unless you need the type information about a polymorphic base there. When do you need that? When you need to de-serialize pointers of the base type.
Hence, if you have
struct A{ virtual ~A(); };
struct B:A{};
struct C:B{};
struct D:B{};`
you will need serialization for A
(but not B
) if you (de)serialize A*
. You will need serialization for B
if you (de)serialize B*
.
Similarly, if your type is not polymorphic (virtual) or you don't use it as such, you don't need any base serialization (e.g. if you (de)serialize C
or D
directly).
Finally, if you have struct A{}; struct B:A{};
there is no need to tell Boost Serialization about the base type at all, (you could just do the serialization from within B
).
case2.cpp needs to call base serialization, of course; not necessarily using base_object because you require polymorphic serialization:
template void serialize(TArchive& archive, unsigned) {
archive & boost::serialization::base_object(*this)
& mData;
// OR:
archive & static_cast(*this)
& mData;
// OR even just:
archive & mParentData
& mData;
}
case3.cpp: indeed, it's exactly like case1, but with dynamic allocation and object tracking
case4.cpp: is exactly like case1, but with dynamic allocation and object tracking; NB!! it requires explicitly serializing for the base!
template void serialize(TArchive& archive, unsigned) {
archive & boost::serialization::base_object(*this)
& mData;
}
case5.cpp: yes, but it's more typical to use the CLASS_EXPORT*
macros from boost/serialization/export.hpp
Bitrot insurance:
- case1.cpp
- case2.cpp
- case3.cpp
- case4.cpp
- case5.cpp