2013-09-28 70 views
1

這個問題已經asked here和其他一些地方,但答案並不真正似乎解決最新Boost庫。如何使std :: shared_ptr使boost :: serialization工作?

爲了說明這個問題,假設我們要序列包含共享指針(std::shared_ptr),具有靜態load功能,將建立從一個文件中的類,並且將實例保存到一個文件save功能沿着類:

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

#include <fstream> 
#include <memory> 
#include <vector> 

class A 
{ 
public: 
    std::shared_ptr<int> v; 

    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 & 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() 
{ 

} 

上面的代碼生成開始c:\local\boost_1_54_0\boost\serialization\access.hpp(118): error C2039: 'serialize' : is not a member of 'std::shared_ptr<_Ty>'錯誤的一個長長的清單,其中據我瞭解應該不是真的因爲我已加載其表面上支持std::shared_ptr升壓shared_ptr序列化庫。我在這裏錯過了什麼?

注:據我瞭解,我的假設boost/serialization/shared_ptr.hpp定義的serialize功能std::shared_ptr是錯誤的,因此正確回答這個問題可能是,我想要麼必須定義std::shared_ptr還是我自己serialize功能轉換爲boost::shared_ptr

回答

1

不,std :: shared_ptr和boost :: shared_ptr是不相關的類模板。

Boost.Serizalization開箱即用不支持std::shared_ptr,但您可以在您的應用程序中添加這樣的支持 - 只需看看<boost/serialization/shared_ptr.hpp>標頭即可。

+0

我是知道的;這是我的問題的基礎。 – arman

+0

@ausairman然後你的問題不清楚。幽州「助推1.54,<...>是應該支持的std :: shared_ptr的」 - 這是不正確。 –

+0

好的。我現在明確表示我正在嘗試使用'boost/serialization/shared_ptr.hpp'標頭。 – arman

2

這是最好的答案我已經能夠拿出自己。如果有人對此有更好的表達,我會接受這個答案來代替。

boost/serialization/shared_ptr.hpp報頭提升附帶不是std::shared_ptrboost::shared_ptr支持。如果你想與共享指針對象序列化工作沒有盜自己的序列代碼,那麼你需要將你std::shared_ptr對象轉換爲boost::shared_ptr對象和live with the consequences

我的誤解是,我認爲boost/serialization/shared_ptr.hppstd::shared_ptr定義了serialize方法。我錯了。

+0

轉換成'的boost :: shared_ptr'我見過店爲析構函數一個可變的λ,通過價值'的std :: shared_ptr'捕獲。所以如果你想序列化這種結構,你仍然需要一種序列化析構函數的方法,因此,也就是'std :: shared_ptr'。所以它的雞和雞蛋的問題。您是否意識到其他轉換的不同之處? – iggy

相關問題