提升multi_index_container序列化

时间:2013-03-20 15:15:58

标签: serialization boost multi-index

我正在尝试将boost :: multi_index_container与boost :: serialization一起使用。但是,当我将指针用作对象作为元素和 non_unique 顺序时,我得到了加载序列化容器的内存访问冲突。我觉得有趣的是,对于唯一排序或使用对象而不是指针作为容器元素,不会发生错误。

有人可以告诉我我的代码是否有问题,或者这是否是升级库中的错误?

以下是产生所述错误的最小示例:

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

#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>

#include <fstream>

using namespace std;
using namespace boost::multi_index;


struct element {

    friend class boost::serialization::access;

    std::string member1;

    element( int num ) { member1 = boost::lexical_cast<string>( num ); }
    element() {}

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & member1;
    }
};

int main( int argc, const char *argv[] )
{

    typedef multi_index_container<element *, indexed_by<ordered_non_unique<member<element, std::string, &element::member1>>>>  TestSet;

    TestSet myset;

    srand( time (NULL ));
    for (int i = 0; i < 20; i++) {
        myset.insert(new element(rand()));  
    }

    // Write set
    ofstream os("test.bin");
    boost::archive::binary_oarchive boa(os);

    boa << myset;
    os.close();

    // Read set
    TestSet newset;
    ifstream is("test.bin");
    boost::archive::binary_iarchive bia(is);

    bia >> newset;

    return 0;
}

1 个答案:

答案 0 :(得分:1)

ofstream os("test.bin");应该是: ofstream os("test.bin", ios::binary);

此外:

ifstream is("test.bin");应该是:ifstream is("test.bin", ios::binary);