c++ - Boost serialization with shared_ptr without implementing serialize() function in pointed class -


in boost tutorial , example of using shared pointers, have class a, , create shared pointer pointing object of class a:

boost::shared_ptr<a> spa(new a); 

then serialize it:

std::ofstream ofs(filename.c_str()); boost::archive::text_oarchive oa(ofs); oa << spa; 

so why class a have have function?

void serialize(archive & ar, const unsigned int /* file_version */);  

the reason want use shared pointer avoid defining function of complex classes. i'm not using shared pointer, i'm using real pointer, , i'm serializing address pointer pointing at.

the reason want use shared_pointer avoid defining function of complex classes.

in opinion, wrong reason use shared pointers. using shared pointers is good, reason memory management you, not have call delete yourself. in (rare) cases, using smart pointers may not best solution , prefer memory management yourself. important criteria decide use smart pointers or not, serialization being side benefit/trouble comes after.

anyway:

i not expert in boost::archive framework, seems serializing class archive more subtle printing value, since uses "version" in case want change how serialize object, ensure retro-compatibility files written older version. why using operator<< of object (in case, either a* or shared_ptr<a>) not enough. do need method void serialize(...).

however, boost provides convenient macro automatically define method shared_ptr<a> objects:

boost_serialization_shared_ptr(a) 

also, guess reason works automagically a* objects there default implementation these.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -