问题在于容器反序列化器正在尝试复制构造 unique_ptr。
为了进行演示,请考虑以下产生相同错误的代码:
std::vector< std::unique_ptr<int> > vec;
std::unique_ptr<int> p;
vec.push_back(p); // does not compile!
然而,这可以通过使用来解决std::move
:
vec.push_back(std::move(p)); // ok
最省力的解决方案是使用可复制构造的智能指针,
例如boost::shared_ptr
,其中带有
其预定义的序列化实现boost/serialization/shared_ptr.hpp
.
下一个解决方案是在类中手动序列化向量:
//NOTE: this replaces void serialize(...) in gps_position
template<class Archive>
void save(Archive & ar, const unsigned int version) const
{
ar & BOOST_SERIALIZATION_NVP(degrees);
size_t size = deg_map.size();
ar & BOOST_SERIALIZATION_NVP(size);
for( auto it=deg_map.begin(), end=deg_map.end(); it!=end; ++it )
ar & boost::serialization::make_nvp("item",*it);
}
template<class Archive>
void load(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(degrees);
size_t size = 0;
ar & BOOST_SERIALIZATION_NVP(size);
deg_map.clear();
deg_map.reserve(size);
while( size-- >= 0 ) {
std::unique_ptr<MyDegrees> p;
ar & boost::serialization::make_nvp("item",p);
deg_map.push_back(std::move(p));
}
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
最后一个解决方案涉及编写您自己的容器序列化器,
就像您对 unique_ptr 所做的那样,它使用std::move
添加项目:
namespace boost { namespace serialization {
//NOTE: do not include boost/serialization/vector.hpp
template<class Archive, class T, class Allocator>
inline void save(
Archive & ar,
const std::vector<T, Allocator> &t,
const unsigned int
){
collection_size_type count (t.size());
ar << BOOST_SERIALIZATION_NVP(count);
for(auto it=t.begin(), end=t.end(); it!=end; ++it)
ar << boost::serialization::make_nvp("item", (*it));
}
template<class Archive, class T, class Allocator>
inline void load(
Archive & ar,
std::vector<T, Allocator> &t,
const unsigned int
){
collection_size_type count;
ar >> BOOST_SERIALIZATION_NVP(count);
t.clear();
t.reserve(count);
while( count-- > 0 ) {
T i;
ar >> boost::serialization::make_nvp("item", i);
t.push_back(std::move(i)); // use std::move
}
}
template<class Archive, class T, class Allocator>
inline void serialize(
Archive & ar,
std::vector<T, Allocator> & t,
const unsigned int file_version
){
boost::serialization::split_free(ar, t, file_version);
}
} } // namespace boost::serialization
最后但并非最不重要的一点是,您应该使用:
oa << BOOST_SERIALIZATION_NVP(g);
// and
ia >> BOOST_SERIALIZATION_NVP(newg);
使用 xml 存档时在 TestBasicSerialize() 中。