boost :: serialization如何与C ++ 11中的std :: shared_ptr一起使用?

时间:2011-11-13 22:21:54

标签: c++ boost c++11 shared-ptr boost-serialization

我知道a Boost moduleserializationboost::shared_ptr,但std::shared_ptr找不到任何内容。

另外,我不知道如何轻松实现它。我担心以下代码

namespace boost{namespace serialization{
template<class Archive, class T>
inline void serialize(Archive & ar, std::shared_ptr<T> &t, const unsigned int version)
{
  if(Archive::is_loading::value) {T*r;ar>>r;t=r;}
  else {ar<<t.get();}
}
}}//namespaces

不起作用。实际上,如果某个对象被多次引用,它将首先加载ar>>r,之后只会复制一个指针。但是我们会创建多个指向它的shared_ptr个对象,因此会多次破坏它。

有关于此的任何想法吗?

我正在使用的系统的一些技术细节:

  • 操作系统:Ubuntu 11.10(x64)
  • 编译器:g ++(Ubuntu / Linaro 4.6.1-9ubuntu3)4.6.1
  • 提升版本:1.46.1(随sudo apt-get install libboost-dev安装)

7 个答案:

答案 0 :(得分:15)

嘿伙计们我终于找到了一个如何使用boost序列化序列化std :: shared_ptr的解决方案。您只需要以下代码(解释如下):

#include <boost/serialization/split_free.hpp>
#include <boost/unordered_map.hpp>

//---/ Wrapper for std::shared_ptr<> /------------------------------------------

namespace boost { namespace serialization {

template<class Archive, class Type>
void save(Archive & archive, const std::shared_ptr<Type> & value, const unsigned int /*version*/)
{
    Type *data = value.get();
    archive << data;
}

template<class Archive, class Type>
void load(Archive & archive, std::shared_ptr<Type> & value, const unsigned int /*version*/)
{
    Type *data;
    archive >> data;

    typedef std::weak_ptr<Type> WeakPtr;
    static boost::unordered_map<void*, WeakPtr> hash;

    if (hash[data].expired())
    {
         value = std::shared_ptr<Type>(data);
         hash[data] = value;
    }
    else value = hash[data].lock();
}

template<class Archive, class Type>
inline void serialize(Archive & archive, std::shared_ptr<Type> & value, const unsigned int version)
{
    split_free(archive, value, version);
}

}}

此代码简单地序列化函数save()中由std :: shared_ptr管理的对象。如果多个std :: shared_ptr实例指向同一个对象,则序列化将自动关注仅存储一次。神奇的事情发生在load()中,其中boost序列化返回一个指向对象(数据)的原始指针。这个原始指针在一个哈希中查找,该哈希为每个原始指针保存一个weak_ptr。如果散列中的weak_ptr过期,我们可以安全地创建一个新的shared_ptr实例,让它管理原始指针并在散列中存储weak_ptr。如果weak_ptr没有过期,我们只需将其锁定即可返回shared_ptr。这样引用计数是正确的。

答案 1 :(得分:13)

从Boost 1.56开始,序列化库对于std :: shared_ptr有built-in support。如果可以使用更新版本的库,则无需实现自己的序列化辅助函数。

答案 2 :(得分:3)

序列化由boost而不是标准库提供,虽然shared_ptr包含在标准中,但它是TR1的一部分(技术报告1)。

截至目前,TR1没有序列化。所以我建议你使用boost的共享指针。

答案 3 :(得分:2)

你还没有说“不起作用”的意思;它不编译?它没有正确加载/存储值?它不是......什么?

我可以在这里找到两个问题,但有一个可能是你有意设计的一部分。

首先,你没有在加载过程中做出正确的指针。让我们分解一下:

inline void serialize(Archive & ar, std::shared_ptr<T> &t, const unsigned int version) {
    if (1) { //unimportant
        T* r;
        ar >> r;
        t = r;
    }
}

当您创建std :: shared_ptr的对象时,您正在实例化一个类模板以提供类似指针的功能(如您所知)。如果你使用int,它将作为int指针。但是,简单地将类型作为T传递并不意味着创建该类型的指针将自动使用该模板;实际上,你正在用T * r创建一个裸指针。它也可能是int * r。然后你无法用new初始化它; r可以指向任何地方。如果用新的正确初始化,你可以获得正确的引用计数来创建/删除该对象;这是std :: shared_ptr似乎不值得我努力的一个领域。我认为裸指针的赋值算作第二个引用,而不是第一个,但我可能错了?无论如何,这不是问题。你可能正在破坏堆;编译器应该发出关于使用未初始化指针的警告,这是一个奇迹,它没有。我希望你没有关闭警告。

如果我没记错的话,r的声明需要替换为:

std::shared_ptr<T> r = new std::shared_ptr<T>;

虽然可能是

std::shared_ptr<T> r = new std::shared_ptr<T>(r());

我暂时没有使用shared_ptr。

顺便说一下,TR1已经出来至少2年了。它基于boost的shared_ptr。我不知道为什么你使用的是Boost 1.46,但我认为它在shared_ptr成为标准的一部分时已经出局了?所以它应该兼容......?

无论如何,第二个潜在的错误来自

t = r;

我假设 - 错误? - 你希望通过重新分配它来将引用计数减少到t(并且可能会破坏对象t指向)。如果您打算复制它,您当然会使用:

*t = *r;

并确保您的复制构造函数正常工作。

答案 4 :(得分:2)

最新版本的Boost Serialization包括对所有标准库智能指针的支持。

答案 5 :(得分:0)

这是对牛仔布的解决方案的改进,它支持加载指向相同内存但具有不同类型的shared_ptr。当归档文件同时包含指向同一对象的shared_ptr和shared_ptr时,会出现此问题,其中A从B继承。

namespace boost {
namespace serialization {

    template<class Archive, class Type>
    void save(Archive & archive, const std::shared_ptr<Type> & value, const unsigned int /*version*/)
    {
        Type *data = value.get();
        archive << data;
    }

    static std::map<void*, std::weak_ptr<void>> hash;

    template<class Archive, class Type>
    void load(Archive & archive, std::shared_ptr<Type> & value, const unsigned int /*version*/)
    {
        Type *data;
        archive >> data;

        if (hash[data].expired())
        {
            std::shared_ptr<void> ptr(data);
            value = static_pointer_cast<Type>(ptr);
            hash[data] = ptr;
        }
        else value = static_pointer_cast<Type>(hash[data].lock());
    }

    template<class Archive, class Type>
    inline void serialize(Archive & archive, std::shared_ptr<Type> & value, const unsigned int version)
    {
        split_free(archive, value, version);
    }

}}

作为这种认识的弱点 - 一张巨大的地图。

答案 6 :(得分:0)

这是基于boost共享指针标题滚动自己的结果,例如基于<boost/serialization/shared_ptr.hpp>

只需复制&amp;将下面的内容粘贴到头文件中并包含它:

#ifndef BOOST_SERIALIZATION_STD_SHARED_PTR_HPP
#define BOOST_SERIALIZATION_STD_SHARED_PTR_HPP

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// shared_ptr.hpp: serialization for boost shared pointer

// (C) Copyright 2004 Robert Ramey and Martin Ecker
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org for updates, documentation, and revision history.

#include <cstddef> // NULL

#include <boost/config.hpp>
#include <boost/mpl/integral_c.hpp>
#include <boost/mpl/integral_c_tag.hpp>

#include <boost/detail/workaround.hpp>
#include <memory>

#include <boost/serialization/split_free.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/tracking.hpp>

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// shared_ptr serialization traits
// version 1 to distinguish from boost 1.32 version. Note: we can only do this
// for a template when the compiler supports partial template specialization

#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
    namespace boost {
    namespace serialization{
        template<class T>
        struct version< ::std::shared_ptr< T > > {
            typedef mpl::integral_c_tag tag;
            #if BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3206))
            typedef BOOST_DEDUCED_TYPENAME mpl::int_<1> type;
            #else
            typedef mpl::int_<1> type;
            #endif
            #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x570))
            BOOST_STATIC_CONSTANT(int, value = 1);
            #else
            BOOST_STATIC_CONSTANT(int, value = type::value);
            #endif
        };
        // don't track shared pointers
        template<class T>
        struct tracking_level< ::std::shared_ptr< T > > {
            typedef mpl::integral_c_tag tag;
            #if BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3206))
            typedef BOOST_DEDUCED_TYPENAME mpl::int_< ::boost::serialization::track_never> type;
            #else
            typedef mpl::int_< ::boost::serialization::track_never> type;
            #endif
            #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x570))
            BOOST_STATIC_CONSTANT(int, value = ::boost::serialization::track_never);
            #else
            BOOST_STATIC_CONSTANT(int, value = type::value);
            #endif
        };
    }}
    #define BOOST_SERIALIZATION_SHARED_PTR(T)
#else
    // define macro to let users of these compilers do this
    #define BOOST_SERIALIZATION_SHARED_PTR(T)                         \
    BOOST_CLASS_VERSION(                                              \
        ::std::shared_ptr< T >,                                     \
        1                                                             \
    )                                                                 \
    BOOST_CLASS_TRACKING(                                             \
        ::std::shared_ptr< T >,                                     \
        ::boost::serialization::track_never                           \
    )                                                                 \
    /**/
#endif

namespace boost {
namespace serialization{

#ifndef BOOST_SERIALIZATION_SHARED_PTR_HPP
struct null_deleter {
    void operator()(void const *) const {}
};
#endif

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// serialization for shared_ptr

template<class Archive, class T>
inline void save(
    Archive & ar,
    const std::shared_ptr< T > &t,
    const unsigned int /* file_version */
){
    // The most common cause of trapping here would be serializing
    // something like shared_ptr<int>.  This occurs because int
    // is never tracked by default.  Wrap int in a trackable type
    BOOST_STATIC_ASSERT((tracking_level< T >::value != track_never));
    const T * t_ptr = t.get();
    ar << boost::serialization::make_nvp("px", t_ptr);
}

template<class Archive, class T>
inline void load(
    Archive & ar,
    std::shared_ptr< T > &t,
    const unsigned int /*file_version*/
){
    // The most common cause of trapping here would be serializing
    // something like shared_ptr<int>.  This occurs because int
    // is never tracked by default.  Wrap int in a trackable type
    BOOST_STATIC_ASSERT((tracking_level< T >::value != track_never));
    T* r;
    ar >> boost::serialization::make_nvp("px", r);
    ar.reset(t,r);
}

template<class Archive, class T>
inline void serialize(
    Archive & ar,
    std::shared_ptr< T > &t,
    const unsigned int file_version
){
    // correct shared_ptr serialization depends upon object tracking
    // being used.
    BOOST_STATIC_ASSERT(
        boost::serialization::tracking_level< T >::value
        != boost::serialization::track_never
    );
    boost::serialization::split_free(ar, t, file_version);
}

} // namespace serialization
} // namespace boost

#endif // BOOST_SERIALIZATION_STD_SHARED_PTR_HPP

您可以查看与<boost/serialization/shared_ptr.hpp> here

的差异

基本上,

  • 重命名为include guard
  • boost::shared_ptr更改为std::shared_ptr
  • 包含<memory>而不是<boost/shared_ptr.hpp>
  • 如果您还使用null_deleter ,则
  • 保护boost::shared_ptr免受重新定义
  • 已删除BOOST_SERIALIZATION_SHARED_PTR_132_HPP - 无论是什么意思?

到目前为止,这似乎工作正常。

相关问题