0

以下のコードでは、拡張子のないファイルに 2 つのオブジェクトを書き込もうとしています。実際には何もファイルに書き込まれないため、問題は書き込み段階で最初に発生します。次に、2番目の部分。読み取り段階では、次の行でファイルを開くと例外が発生します。

ブースト::アーカイブ::text_iarchive ia(ifs);

これはブーストの例 1 から取得しました。また、このページのこの問題に対する 3 番目の回答に従ってみましたBoost Serialization multiple objects

    #include <fstream>

// include headers that implement a archive in simple text format
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
/////////////////////////////////////////////////////////////
// gps coordinate
//
// illustrates serialization for a simple type
//
class gps_position
{
    private:
        friend class boost::serialization::access;
    // When the class Archive corresponds to an output archive, the
    // & operator is defined similar to <<.  Likewise, when the class Archive
    // is a type of input archive the & operator is defined similar to >>.
        template<class Archive>
        void serialize(Archive & ar, const unsigned int version)
        {
            ar & degrees;
            ar & minutes;
            ar & seconds;
        }
        int degrees;
        int minutes;
        float seconds;
    public:
        gps_position(){};
        gps_position(int d, int m, float s) :
        degrees(d), minutes(m), seconds(s)
    {}
};
int main()
{
    // create and open a character archive for output
    std::ofstream ofs("filename",std::ios::app);

    // create class instance

    gps_position g0(35, 59, 24.567f);
    gps_position g1(35, 59, 88.567f);
    // save data to archive
    //{
        boost::archive::text_oarchive oa(ofs);
        // write class instance to archive
        size_t number_of_objects = 2;
        oa << number_of_objects;
        oa << g0;
        oa << g1;
        // archive and stream closed when destructors are called
   // }

    // ... some time later restore the class instance to its orginal state

    gps_position newg0;
    gps_position newg1;
   // {
        // create and open an archive for input
        std::ifstream ifs("filename");
        boost::archive::text_iarchive ia(ifs);
        // read class state from archive


        ia >> number_of_objects;
        ia >> newg0;
        ia >> newg1;
        // archive and stream closed when destructors are called
    //}

    return 0;
}
4

1 に答える 1

2

書き込み段階を囲む中括弧のコメントを外します。それ以外の場合、アーカイブも、std::ofstream読み取りを試みる前に閉じられません。

std::ofstreamコメントで何人かの人が述べているように、ストリームはフラッシュして閉じる必要があります。これは、 ;のインスタンスを破棄するときに自動的に行われます。その場合、書き込み段階の閉じ中括弧に遭遇したとき。

于 2013-01-23T14:20:57.643 に答える