Search code examples
c++boostc++11shared-ptrboost-serialization

How can boost::serialization be used with std::shared_ptr from C++11?


I know that there is a Boost module for serialization of boost::shared_ptr, but I cannot find anything for 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

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.

Any ideas on that?

Some technical details about the system I'm using:

  • OS: Ubuntu 11.10 (x64)
  • Compiler: g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
  • boost version: 1.46.1 (installed with sudo apt-get install libboost-dev)

Solution

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