boost::serialization 如何与 C++11 中的 std::shared_ptr 一起使用?

我知道有一个Boost模块序列化的boost::shared_ptr,但我找不到任何东西对于 std::shared_ptr.

另外,我不知道如何轻松实现它.恐怕下面的代码

Also, I don't know how to implement it easily. I'm afraid that the following code

namespace boost{namespace serialization{
template<class Archive, class T>
inline void serialize(Archive & ar, std::shared_ptr<T> &t, const unsigned int version)
{
  if(Archive::is_loading::value) {T*r;ar>>r;t=r;}
  else {ar<<t.get();}
}
}}//namespaces

不起作用.事实上,如果某个对象被多次引用,它将在第一次运行 ar>>r 时加载,然后只复制一个指针.然而,我们会创建多个指向它的 shared_ptr 对象,因此会多次破坏它.

doesn't work. Indeed, if some object was referred multiple times, it would be loaded with first run of ar>>r, and after that just a pointer will be copied. However we would create multiple shared_ptr objects pointing to it, and therefore would destruct it more than one time.

对此有什么想法吗?

关于我正在使用的系统的一些技术细节:

Some technical details about the system I'm using:

  • 操作系统:Ubuntu 11.10 (x64)
  • 编译器:g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
  • boost 版本:1.46.1(使用 sudo apt-get install libboost-dev 安装)

推荐答案

从 Boost 1.56 开始,序列化库有 对 std::shared_ptr 的内置支持.如果您可以使用该库的更新版本,则无需实现自己的序列化辅助函数.

As of Boost 1.56, the serialization library has built-in support for std::shared_ptr. You do not need to implement your own serialization helper functions if you can use a more recent version of the library.

相关文章