Loading and saving a class to a binary file
I don't know if this is possible but, I have a class and I'v made an instance of it. I also put things in it. It has vectors and other things. I was wondering if I could save its contents (the instance) to a binary file, then reload it and 开发者_Go百科cast it in from the file. Thanks
Yes, sometimes, kinda...
Serialization is a tricky problem. Don't solve it yourself (i.e. don't reinvent the wheel... plenty of smart people have already done this). What you've described works in a constrained environment:
- Your reading and writing machines have the same endianness.
- Your class contains data only within its footprint (no pointers or objects with pointers).
- This isn't for the real world
- the real world usually needs something better
- the real world usually wants backwards compatible against changes
- the real world usually can't anticipate hardware changes
You probably want to look into different serialization schemes. They have their own pluses and minuses, which you'll find plenty of information detailing on StackOverflow.
To get you started, look into Google's protocol buffers, boost serialization and XML.
Whenever there's a C++ question, the answer is likely to be Boost. Check Boost Serialization.
An alternative to boost, if you want is s11n
精彩评论