Boost logo

Boost Users :

Subject: Re: [Boost-users] [Serialization] shared_ptr to const object
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2009-12-18 20:46:36


AMDG

elizabeta petreska wrote:
> How to serialize shared_ptr member which points to const object.
> The following compiles, but is not working i.e the restored
> boost_shared_ptr does not point to anything.
> I tried to use const_pointer_cast to cast the const away. I suspect that
> this is the problematic part.
>
> I think the question here is , how should I cast away the const correctly
> for boost::shared_ptr<const T>?
>

The problem is that you are creating a temporary when
you do the cast. When you deserialize, the temporary
is modified, instead of mac. The following seems to
work.

#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/utility.hpp>
#include <fstream>
#include <boost/serialization/shared_ptr.hpp>

class B
{
public:
    B() { }
    B(int a):ma(a) { }

    int ma;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int
        /*version*/)
    {
        using boost::serialization::make_nvp;
        ar & make_nvp("ma",ma);
    }
};

class BC
{
public:
    BC() { }
    BC(boost::shared_ptr<B>& t):mac(t) { }

    boost::shared_ptr<const B> mac;

    BOOST_SERIALIZATION_SPLIT_MEMBER()

    template<class Archive>
    void save(Archive & ar, const unsigned int /*version*/) const
    {
        using boost::serialization::make_nvp;
        ar & make_nvp("mac", mac);
    }
    template<class Archive>
    void load(Archive & ar, const unsigned int /*version*/)
    {
        using boost::serialization::make_nvp;
        boost::shared_ptr<B> temp;
        ar & make_nvp("mac", test);
        mac = temp;
    }
};

int main()
{
    std::ofstream ofs(L"C:\\MyTest.xml");
    std::ifstream ifs(L"C:\\MyTest.xml");

    boost::shared_ptr<B> bb(new B(4));

    BC aa(bb);

    {
        boost::archive::xml_oarchive oa(ofs);
        oa & BOOST_SERIALIZATION_NVP(aa);
    }

    BC raa;
    {
        boost::archive::xml_iarchive ia(ifs);
        ia & BOOST_SERIALIZATION_NVP(raa);
    }

}

In Christ,
Steven Watanabe


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