gpt4 book ai didi

c++ - 如何将二进制文件反序列化为对象?

转载 作者:行者123 更新时间:2023-12-02 10:16:28 26 4
gpt4 key购买 nike

我使用这种方法来序列化我的对象:

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));
}

我的 Obj load(string fileName)的代码是什么?

最佳答案

基本上与您拥有的相同:

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;
}

当然,这是 ,假设您的类型可与 make_binary_object一起使用:确保 Obj可按位序列化(POD):
    static_assert(std::is_pod<Obj>::value, "Obj is not POD");

另外,重新考虑 using namespace: Why is "using namespace std;" considered bad practice?

关于c++ - 如何将二进制文件反序列化为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61772931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com