2013-09-29 37 views
1

我想使用boost的功能來序列化指向原語的指針(這樣我就不必去引用並自己做一個深層存儲)。但是,當我嘗試這樣做時,我會遇到一堆錯誤。下面是一個簡單的例子,該類應該包含saveload方法,它們從文件中讀寫類內容。這個程序不編譯:如何序列化包含指向基元的指針的類?

#include <boost/archive/text_iarchive.hpp> 
#include <boost/archive/text_oarchive.hpp> 

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

#include <fstream> 

class A 
{ 
public: 
    boost::shared_ptr<int> sp; 
    int const * p; 

    int const& get() {return *p;} 

    void A::Save(char * const filename); 
    static A * const Load(char * const filename); 

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

// save the world to a file: 
void A::Save(char * const filename) 
{ 
    // create and open a character archive for output 
    std::ofstream ofs(filename); 

    // save data to archive 
    { 
     boost::archive::text_oarchive oa(ofs); 

     // write the pointer to file 
     oa << this; 
    } 
} 

// load world from file 
A * const A::Load(char * const filename) 
{ 
    A * a; 

    // create and open an archive for input 
    std::ifstream ifs(filename); 

    boost::archive::text_iarchive ia(ifs); 

    // read class pointer from archive 
    ia >> a; 

    return a; 
} 

int main() 
{ 

} 

注意,我不感興趣在取消引用指針的解決方案;我希望能夠爲我提供幫助(其中許多類可能指向相同的基礎對象)。

+0

,你會得到錯誤...? – john

回答

2

http://www.boost.org/doc/libs/1_54_0/libs/serialization/doc/index.html

默認情況下,數據類型指定原始通過執行層面 類的序列特徵,無需跟蹤。如果希望通過指針跟蹤 一個共享原語對象(例如,用作引用計數的長整型),它應該被包裝在一個類/結構中,以便它是可識別類型的 。改變長度的實施 級別的替代方案將會影響整個程序中的所有長整數 - 可能不是人們想要的。

因此:

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

boost::shared_ptr<Wrapped> sp; 
Wrapped const * p; 
+0

這是一個非常有用的答案,它花了很長時間才能通過搜索找到。如果任何人有興趣使用boost來序列化類中的二進制數據,例如unsigned char *類型的成員,最好的選擇是將這個數據包裝在一個向量中。即MyClass :: vector binary_data。然後,您可以從MyClass中以&binary_data [0]的形式訪問c數組,並且整個向量可以通過boost輕鬆地序列化。 – SullX

相關問題