Note that there are some explanatory texts on larger screens.

plurals
  1. POc++ boost serialization with stringstream
    text
    copied!<p>I am new to boost and c++ and is attempting to serialize an object to binary and then unserialize it.</p> <p>I'm using the classes from the example in: <a href="http://en.highscore.de/cpp/boost/serialization.html" rel="noreferrer">http://en.highscore.de/cpp/boost/serialization.html</a></p> <p>So suppose this is the class I am trying to serialize: </p> <pre><code>class person { public: person() { } person(int age) : age_(age) { } int age() const { return age_; } private: friend class boost::serialization::access; template &lt;typename Archive&gt; void serialize(Archive &amp;ar, const unsigned int version) { ar &amp; age_; } int age_; }; </code></pre> <p>This is the serialization code: </p> <pre><code>const char * save(Object ss) { boost::archive::binary_oarchive oa(ss); person p(31); oa &lt;&lt; p; return ss.str().data(); } </code></pre> <p>This is the unserialization code:</p> <pre><code>void load(const char * str) { stringstream s; s &lt;&lt; str; boost::archive::binary_iarchive ia(s); person p; ia &gt;&gt; p; std::cout &lt;&lt; p.age() &lt;&lt; std::endl; } </code></pre> <p>When I attempt to run this code, I receive this error:</p> <pre><code>terminate called after throwing an instance of 'boost::archive::archive_exception' what(): stream error </code></pre> <p>Which brings me to ask, is there a proper way of doing this? </p> <p>Thanks, much appreciated. </p> <p>EDIT: This version works: </p> <p>This is the serialization code: </p> <pre><code>string save() { boost::archive::binary_oarchive oa(ss); person p(31); oa &lt;&lt; p; return ss.str(); } </code></pre> <p>This is the unserialization code:</p> <pre><code>void load(string str) { stringstream s; s &lt;&lt; str; boost::archive::binary_iarchive ia(s); person p; ia &gt;&gt; p; std::cout &lt;&lt; p.age() &lt;&lt; std::endl; } </code></pre> <p>EDIT2: This version does not work. Would appreciate comments on a fix. Thanks.</p> <pre><code>void Serialization::save() { stringstream ss; { boost::archive::binary_oarchive oa(ss); person p(31); oa &lt;&lt; p; } const char * temp1 = ss.str().data(); stringstream s; s &lt;&lt; temp1; cout &lt;&lt; "UNSERIALIZING\n"; boost::archive::binary_iarchive ia(s); person p1; ia &gt;&gt; p1; std::cout &lt;&lt; p1.age() &lt;&lt; std::endl; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload