开发者

boost::Serialize VS std::fstream

Hey so i guess i'm a little confused on the purpose of boost::serialize:

Having to add a boost::serialize function to every class you plan to save seems to kind of defeat the purpose of t开发者_JAVA技巧he library, as instead of boosting/ decreasing development time it seems like it would add a HUGE amount of time since you have to go in and edit the source of every class in every library your using so it has a Serialization function.

I was planning on using it for a SFML/Box2D game, but now i'm having second thoughts once i think this through.... I'm i using the library wrong?

It seems like std::fstream would be a much better idea, as that doesn't require any functions or changes to be made to whatever class you want to save, and i could design a "Save class."


Er, what? Boost.Serialization is not a replacement for I/O streams. It's a framework for serialisation (i.e. saving and restoring the state of an object from an external storage), the archives still wrap some kind of stream to actually read and write data. Of course you need to write serialising functions, the library has no way of knowing where the data, or how should it be layed out in the archive otherwise — if you'd use fstream, whatever that means in this context, you'd still have to do the same. You don't necessarily need to implement the save/load functions as class members, either — the documentation says how to make them as free functions.


Writing directly to a standard stream would still require you to write a serialization/deserialization function pair. Not only the iostream component of the standard library does not support I/O of custom classes, but just writing and reading back sizeof(yourObject) bytes wouldn't work. Just think about what would happen if your class contained pointer members.

Moreover the serialization library provides feature like support for different formats and versioning, which may be useful.


It seems like std::fstream would be a much better idea, as that doesn't require any functions or changes to be made to whatever class you want to save, and i could design a "Save class."

A better idea to do what?

Serialization is typically used for saving and restoring the state of objects, not arbitrary data. It's purpose is to be able to take a bag of objects and produce a file, such that these objects can be automatically reconstructed from that file at a later date.

If you can collate all of the information you want to save into a "save class", then you don't need serialization.

Also, you cannot just write a class to a stream; you would have to implement a operator<< overload or some other function to save its data and load it back. Yes, you could just throw the bits of the object out with memcpy, but that's not exactly safe. And by "not exactly safe", I mean "you should never do this unless you really, really know what you're doing."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜