[英]How to unserialize a binary file into an object?
I used this method to serialize my object:我使用这种方法来序列化我的 object:
void save(Obj& obj) {
ofstream os("obj.dat", ofstream::binary);
boost::archive::binary_oarchive ar(os, boost::archive::no_header);
ar << boost::serialization::make_binary_object(&obj, sizeof(obj));
}
What would be my the code for my Obj load(string fileName)
?我的Obj load(string fileName)
的代码是什么?
It's basically the same as what you had:它与您所拥有的基本相同:
Obj load(std::string const& filename) {
std::ifstream is(filename, std::ios::binary);
boost::archive::binary_iarchive ar(is, boost::archive::no_header);
Obj obj;
ar >> boost::serialization::make_binary_object(&obj, sizeof(obj));
return obj;
}
Of course, this is assuming that your type is valid for use with make_binary_object
: make sure that Obj
is bitwise serializable (POD):当然,这是假设您的类型可以与make_binary_object
一起使用:确保Obj
是按位可序列化 (POD) 的:
static_assert(std::is_pod<Obj>::value, "Obj is not POD");
Also, reconsider using namespace
: Why is "using namespace std;"另外,重新考虑using namespace
: 为什么是“使用命名空间标准;” considered bad practice? 被认为是不好的做法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.