When used for serialize the shared pointer, memory leak occurs.

I am not sure that is due to the internal bug or the wrong use of serialization library.

The following is test code:

 

 

==================================================================================

#include <iostream>

#include <cstddef>

#include <fstream>

#include <string>

#include <cstdio>

#include <boost/config.hpp>

#include <boost/archive/tmpdir.hpp>

#include <boost/archive/text_oarchive.hpp>

#include <boost/archive/text_iarchive.hpp>

#include <boost/serialization/shared_ptr.hpp>

 

class A{

  private:

    friend class boost::serialization::access;

    int x;

    template<class Archive>

      void serialize(Archive& ar, const unsigned int /* file version */)

      {

        ar & x;

      }

  public:

    static int count;

    A(){++count; std::cout<<"A ctor"<<std::endl;}

    virtual ~A(){--count;std::cout<<"A dtro"<<std::endl;}

};

 

int A::count = 0;

 

int main(int /* argc */, char /*argv[]  */){

  std::string filename(boost::archive::tmpdir());

  filename += "/testfile";

  boost::shared_ptr<A> spa(new A);

  {

    std::ofstream ofs(filename.c_str());

    boost::archive::text_oarchive oa(ofs);

    oa << spa;

  }

  spa.reset();

  {

    std::ifstream ifs(filename.c_str());

    boost::archive::text_iarchive ia(ifs);

    ia >> spa;

  }

  spa.reset();

  std::cout << std::endl;

  return 0;

}

==================================================================================

The output is:

A ctor

A dtor

A ctor

 

Valgrind report memory leak of 8 bytes, just the size of class A.