Common confusions with serializing polymorphic types

后端 未结 2 1961
野的像风
野的像风 2021-01-20 07:51

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

2条回答
  •  滥情空心
    2021-01-20 08:16

    • 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

    • The usefulness of 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

    • Requiring 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).

    Update in response to your samples:

    1. case1.cpp looks ok
    2. 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;
      }
      
    3. case3.cpp: indeed, it's exactly like case1, but with dynamic allocation and object tracking

    4. 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;
      }
      
    5. 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

提交回复
热议问题