【问题标题】:Boost serialization: SIGABRT while deserializing boost::shared_ptr on object containing std::shared_ptrBoost 序列化:SIGABRT 同时对包含 std::shared_ptr 的对象反序列化 boost::shared_ptr
【发布时间】:2019-03-26 08:24:37
【问题描述】:

我正在尝试对包含std::shared_ptr 的对象执行boost::shared_ptr 的序列化和反序列化。

为此,我使用boost::archive::binary_oarchiveboost::archive::binary_iarchive。一切都很好,但是当binary_iarchive 实例超出范围时,我得到了 SIGABRT。这是我的代码:

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/serialization.hpp>

#include <boost/serialization/shared_ptr.hpp>
#include <sstream>

#include <boost/shared_ptr.hpp>

class SomeClass
{
private:
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive &ar, const unsigned int file_version) {
    }
};

class ClassWithStdSharedPointer
{
public:
    std::shared_ptr<SomeClass> ptr_to_someclass;

    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive &ar, const unsigned int file_version)
    {
        ar & ptr_to_someclass;
    }
};

int main()
{
    boost::shared_ptr<const ClassWithStdSharedPointer> ptr_to_save;
    ptr_to_save = boost::make_shared<ClassWithStdSharedPointer>();

    std::ostringstream ostream;
    boost::archive::binary_oarchive oa(ostream);
    oa << ptr_to_save;

    std::string serialized_buffer = ostream.str();
    std::istringstream istream(serialized_buffer);

    {
        boost::archive::binary_iarchive ia(istream);

        boost::shared_ptr<ClassWithStdSharedPointer> ptr_to_load;

        ia >> ptr_to_load;
    } 
} // the problem appears when you get to this line

我使用的是 boost 1.62,它允许序列化 std::shared_ptr's。

经过一番研究,我发现当调用shared_ptr_helper 类析构函数时会发生SIGABRT(相关代码可以在boost 库的文件serialization/shared_ptr_helper.hpp 中找到)。该类有一个std::map 的实例,用于存储反序列化的指针。

std::shared_ptr 的序列化代码与boost::shared_ptr 的序列化代码几乎相同(文件serialization/shared_ptr.hpp)。事实上,它们都使用shared_ptr_helper 的单个实例。因此,上述std::map 包含shared_ptr 的两种类型,但它应该只包含一种类型,这会在调用析构函数时导致 SIGABRT。

序列化代码通过上面在serialization/shared_ptr.hpp 中定义的ID 获取帮助程序。如果我们对不同类型的shared_ptr 使用不同的ID,问题就消失了。我知道这样做是为了处理指向同一对象的多个指针被序列化的情况,但在这种情况下似乎不太可能有人同时使用std::shared_ptrboost::shared_ptr

那么,这里发生了什么?使用这两种类型的 shared_ptr 是不好的做法,我应该只选择其中一种,否则 boost 中存在错误?

【问题讨论】:

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


    【解决方案1】:

    我找到了question,其中讨论了shared_ptr_helper 的另一个问题。看起来那个类实际上有一些设计缺陷,所以在我的例子中,我应该只在我的代码中留下一种类型的shared_ptr

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 2012-10-05
      • 2015-01-22
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多