Boost logo

Boost Users :

From: Mikko Vainio (mikko.vainio_at_[hidden])
Date: 2006-11-22 05:46:07


Hi,

I'm trying to serialize an object of class X that has a member
boost::weak_ptr< X >. The weak pointer may as well be empty and the
object is still in valid state - at least in this context. The
serialization code, however, tries to make a shared_ptr out of the
weak_ptr, which throws a bad_weak_ptr when the weak_ptr is empty. Should
the weak_ptr be checked for expired() before trying to make a shared_ptr
of it?

Using boost 1.33.1 on Fedora Core 6, gcc 4.1.1, glibc 2.5, though the
platform should not matter here.

An example code demonstrating the problem follows:

#include <iostream>
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/weak_ptr.hpp>

class X
{
public:

        template< typename Archive >
        void serialize(Archive & ar, const unsigned int version)
        {
                ar & some_data;
                ar & myFellowClassmate;
        }

        boost::weak_ptr< X > myFellowClassmate;
        int some_data;
};

inline std::ostream& operator<<( std::ostream& os, const X& x )
{
        return os << "x.some_data = " << x.some_data << std::endl;
}

using namespace std;

int main ( int argc, char* argv[] )
{
        X x;
        x.some_data = 1;
        cout << x;
        std::ofstream ofs("filename");
        boost::archive::text_oarchive oa(ofs);
        oa & x;
        ofs.close();
        std::ifstream ifs("filename", std::ios::binary);
        boost::archive::text_iarchive ia(ifs);
        x.some_data = 3;
        cout << x;
        ia & x;
        cout << x; // should print out 'x.some_data = 1'
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net