Boost logo

Boost Users :

Subject: Re: [Boost-users] [Serialization] shared_ptr to const object
From: elizabeta petreska (elizabeta.petreska_at_[hidden])
Date: 2009-12-20 07:05:10


Thank you for the reply.
This works!!! , but it creates a temporary. I was thinking how to cast the
constness away, without making temporary object. I gess know at least I have
one possible solution, althgough not complete happy with it :)

On 12/19/09, Steven Watanabe <watanabesj_at_[hidden]> wrote:
>
> 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 mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>



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