Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2004-11-10 10:14:41


Robert Ramey wrote:
> I wasn't able to do this with shared_ptr and its becoming apparent
> that its not going to be obvious on how to do it.

Serializing a shared_ptr is both trivial and very difficult. Reminds me of
the difference between a magazine article and a real production-level
implementation. But it doesn't need any access to the physical
representation, at least conceptually.

I don't have much time in the moment, so I'll just offer the example below.
More, including deserialization, later.

#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <iostream>
#include <vector>
#include <map>
#include <string>

std::map< boost::shared_ptr<void>, int > wpmap;

void write( std::ostream & os, int const & v )
{
    os << v << ' ';
}

void write( std::ostream & os, std::string const & v )
{
    os << v << ' ';
}

template<class T> void write( std::ostream & os, boost::shared_ptr<T> const
& pt )
{
    if( pt )
    {
        int pid = wpmap[ pt ];

        if( pid != 0 )
        {
            write( os, pid );
        }
        else
        {
            pid = wpmap.size();
            wpmap[ pt ] = pid;
            write( os, pid );
            write( os, *pt );
        }
    }
    else
    {
        write( os, 0 );
    }
}

template<class T> void write( std::ostream & os, boost::weak_ptr<T> const &
pt )
{
    write( os, pt.lock() );
}

template<class T> void write( std::ostream & os, std::vector<T> const & v )
{
    write( os, (int)v.size() );

    for( size_t i = 0; i < v.size(); ++i )
    {
        write( os, v[i] );
    }
}

int main()
{
    std::vector< boost::shared_ptr<std::string> > v1;
    std::vector< boost::weak_ptr<std::string> > v2;

    v1.push_back( boost::shared_ptr<std::string>(new std::string("S1")) );
    v1.push_back( v1[0] );
    v1.push_back( boost::shared_ptr<std::string>(new std::string("S2")) );
    v1.push_back( v1[0] );
    v1.push_back( boost::shared_ptr<std::string>(new std::string("S3")) );
    v1.push_back( v1[0] );
    v1.push_back( v1[2] );

    v2.push_back( v1[0] );
    v2.push_back( v1[0] );
    v2.push_back( v1[2] );

    write( std::cout, v2 );
    write( std::cout, v1 );
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk