2015-04-29 70 views
1

我有上面的方法序列化一個泛型類。在boost :: archive :: binary_iarchive上std :: bad_alloc

std::unique_ptr<Message> Serializer::deserialize(char* data , int size) { 
    std::stringstream ss(std::ios_base::in | 
          std::ios_base::out | 
          std::ios_base::binary); 
    ss.write(data, size); 
    Message *in; 

    boost::archive::binary_iarchive ia(ss, boost::archive::no_header); 
    ia >> in; 
    return std::unique_ptr<Message> (in); 
} 

我得到

terminate called after throwing an instance of 'std::bad_alloc' 
    what(): std::bad_alloc 

,當我嘗試調用上一個char *,我肯定一體發送反序列化。 我嘗試反序列化的類,可以在這裏找到:

class DiscoveryMessage : public Message { 
public: 

    DiscoveryMessage() {} 

    DiscoveryMessage(int tcpPort); 

    virtual ~DiscoveryMessage(){} 

    friend class boost::serialization::access; 

private: 
    template <class Archive> 
    void serialize(Archive &ar, const unsigned int) { 
    // invoke serialization of base class (Message) 
    ar & boost::serialization::base_object<Message>(*this); 
    ar & mTcpReceivePort; 
    ar & mIPAddr; 
    } 

    int mTcpReceivePort; 
    std::string mIPAddr; 
}; 

回答

0

確保你真的反序列化相同的類型,你係列化。

具體來說,我看你在unique_ptr和派生類中混合。例如。你不能用上面的代碼進行反序列化DiscoveryMessage*boost::shared_ptr<Message>

簡單的演示:

Live On Coliru

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

class DiscoveryMessage; 
struct Message { 
    virtual ~Message() {} 

    virtual void do_print(std::ostream& os) const { os << "(base)"; } 

    friend std::ostream& operator<<(std::ostream& os, Message const& m) { 
     m.do_print(os); 
     return os; 
    } 

    template <class Archive> void serialize(Archive &ar, const unsigned int) { 
     ar.template register_type<DiscoveryMessage>(); 
    } 
}; 

class DiscoveryMessage : public Message { 
    public: 
    DiscoveryMessage() {} 

    DiscoveryMessage(int tcpPort) : mTcpReceivePort(tcpPort) {} 
    virtual void do_print(std::ostream& os) const { 
     os << "{" << mIPAddr << ":" << mTcpReceivePort << "}"; 
    } 

    private: 
    friend class boost::serialization::access; 
    template <class Archive> void serialize(Archive &ar, const unsigned int) { 
     // invoke serialization of base class (Message) 
     ar & boost::serialization::base_object<Message>(*this); 
     ar & mTcpReceivePort; 
     ar & mIPAddr; 
    } 

    int mTcpReceivePort; 
    std::string mIPAddr = "hello"; 
}; 

BOOST_CLASS_EXPORT(Message) 
BOOST_CLASS_EXPORT(DiscoveryMessage) 

#include <sstream> 
#include <iostream> 

int main() 
{ 
    std::stringstream ss; 
    { 
     boost::archive::text_oarchive oa(ss); 
     Message * p = new DiscoveryMessage(42); 
     oa << p; 
    } 

    { 
     boost::archive::text_iarchive ia(ss); 
     Message * p; 
     ia >> p; 
     std::cout << *p << "\n"; 
    } 
} 

打印

{hello:42} 
相關問題