核心是直接内存写入,通过write/read函数序列化POD类型;非POD需手动处理字段,如先存字符串长度再存内容,确保跨平台兼容性与资源安全。

在C++中实现二进制对象序列化,核心是将对象的内存布局直接写入文件,读取时再按相同格式还原。这种方式高效且紧凑,适合保存自定义类型或复杂数据结构。
基本原理:直接内存写入
二进制序列化依赖于 write() 和 read() 函数,它们以字节流形式操作数据。
对于POD(Plain Old Data)类型,可以直接写入内存块:
#include#include struct Point { int x; int y; }; void savePoint(const Point& p, const std::string& filename) { std::ofstream file(filename, std::ios::binary); file.write(reinterpret_cast (&p), sizeof(p)); file.close(); } void loadPoint(Point& p, const std::string& filename) { std::ifstream file(filename, std::ios::binary); file.read(reinterpret_cast (&p), sizeof(p)); file.close(); }
处理非POD类型和复杂对象
类中包含指针、STL容器(如 string、vector)时,不能直接写入,因为它们指向堆内存。
立即学习“C++免费学习笔记(深入)”;
解决方案是手动序列化每个字段:
struct Person {
std::string name;
int age;
void save(std::ofstream& file) const {
// 先写字符串长度
size_t len = name.size();
file.write(reinterpret_cast(&len), sizeof(len));
// 再写字符串内容
file.write(name.c_str(), len);
// 写基本类型
file.write(reinterpret_cast(&age), sizeof(age));
}
void load(std::ifstream& file) {
size_t len;
file.read(reinterpret_cast(&len), sizeof(len));
name.resize(len);
file.read(&name[0], len);
file.read(reinterpret_cast(&age), sizeof(age));
}
};
使用RAII管理文件流
建议将文件操作封装在函数中,利用局部对象自动析构来关闭文件,避免资源泄漏。
示例用法:
void savePerson(const Person& p, const std::string& filename) {
std::ofstream file(filename, std::ios::binary);
if (file) {
p.save(file);
}
}
void loadPerson(Person& p, const std::string& filename) {
std::ifstream file(filename, std::ios::binary);
if (file) {
p.load(file);
}
}
基本上就这些。只要注意内存布局、大小端问题(跨平台时)和非POD类型的处理,二进制序列化就能可靠工作。不复杂但容易忽略细节。










