簡體   English   中英

使用 map 增強二進制序列化,並在序列化時加倍崩潰

[英]Boost binary serialization with a map and doubles crashes on serialize in

這是代表我的問題的示例。 除非 finalTime 大於 25,否則 map 將完全正常地序列化。通過 boost 單元測試,我得到了 std::exception 輸入 stream 錯誤。 此外,此代碼使用 polymorphic_text_archives 也能正常工作。 讀取 map 時發生錯誤。

#include <fstream>
#include <iostream>
#define BOOST_ALL_DYN_LINK
#define BOOST_PARAMETER_MAX_ARITY 8
#include <boost/serialization/export.hpp>
#include <boost/archive/polymorphic_iarchive.hpp>
#include <boost/archive/polymorphic_oarchive.hpp>
#include <boost/archive/polymorphic_binary_iarchive.hpp>
#include <boost/archive/polymorphic_binary_oarchive.hpp>
#include <boost/static_assert.hpp>
#include <boost/serialization/map.hpp>

using namespace boost;

class DoubleTest
{
public:
    DoubleTest(double d)
    {
        this->Double = d;
    }

    DoubleTest()
    {
        this->Double = 0;
    }

    void serialize(boost::archive::polymorphic_iarchive & ar, const unsigned int)
    {
        ar & this->Double;
    }

    void serialize(boost::archive::polymorphic_oarchive & ar, const unsigned int)
    {
        ar & this->Double;
    }

    double Double;
};

int main(int argc, char** argv)
{
    const std::string fileName = "test.out";
    std::map<float, DoubleTest*> mymap;

    const int initialValue = 0;
    const int initialTime = 0;

    // A "finalTime" of 25 works. "26" does not.
    const int finalTime = 26;
    int value = 10;

    // Put values into the map.
    for(int time = initialTime; time < finalTime; time += 1)
    {
        value++;
        mymap[time] = new DoubleTest(value);
    }

    // Write a binary archive out.
    std::ofstream ofs(fileName.c_str());
    boost::archive::polymorphic_binary_oarchive oa(ofs);
    oa << mymap;
    ofs.flush();
    ofs.close();

    // Create a new map to read the binary archive into.
    std::map<float, DoubleTest*> mymap2;

    // Read in the new binary archive.
    std::ifstream ifs(fileName.c_str());
    boost::archive::polymorphic_binary_iarchive ia(ifs);
    ia >> mymap2;
    ifs.close();

    // Loop through the values to make sure they are correct.
    std::map<float, DoubleTest*>::iterator it; 
    for(it = mymap2.begin(); it != mymap2.end(); ++it)
    {
        std::cout << "Key: " << it->first << " ";
        std::cout << "Value: " << it->second->Double << '\n';
    }

    int pause;
    std::cin >> pause;
}

您需要序列化為二進制文件 stream。 將 ios_base::binary 添加到 stream 構造函數中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM