C++序列化需手动或借助库实现,常见方法有:1. 手动编写serialize/deserialize函数,控制精细但维护成本高;2. 使用Boost.Serialization库,支持多种格式与复杂类型,适合大型项目;3. 采用nlohmann/json库进行JSON序列化,可读性好,适用于配置与网络通信;4. 使用Google Protocol Buffers,通过.proto文件定义结构,生成高效二进制序列化代码,性能优、跨语言,适合高性能服务通信。选择依据需求:调试用JSON,性能关键选Protobuf或Boost,轻量场景可手写,注意状态完整性、字节序与版本兼容。

在C++中,序列化是指将对象的状态转换为可以存储或传输的格式(如字节流、JSON、XML等),反序列化则是将其还原为原来的对象。由于C++标准库没有内置的序列化机制,实现序列化通常需要手动编写代码或借助第三方库。以下是几种常见的C++对象序列化方法。
1. 手动序列化与反序列化
最直接的方法是自己定义序列化逻辑,通过重载和>>操作符或提供serialize和deserialize成员函数。
例如,有一个简单的Person类:
class Person {
public:
std::string name;
int age;
// 序列化到输出流
void serialize(std::ostream& out) const {
size_t name_len = name.size();
out.write(reinterpret_cast(&name_len), sizeof(name_len));
out.write(name.c_str(), name_len);
out.write(reinterpret_cast(&age), sizeof(age));
}
// 从输入流反序列化
void deserialize(std::istream& in) {
size_t name_len;
in.read(reinterpret_cast(&name_len), sizeof(name_len));
name.resize(name_len);
in.read(&name[0], name_len);
in.read(reinterpret_cast(&age), sizeof(age));
}
};
使用时可配合std::ofstream和std::ifstream进行文件读写:
立即学习“C++免费学习笔记(深入)”;
Person p{"Alice", 25};
// 序列化
std::ofstream ofs("person.dat", std::ios::binary);
p.serialize(ofs);
ofs.close();
// 反序列化
Person p2;
std::ifstream ifs("person.dat", std::ios::binary);
p2.deserialize(ifs);
ifs.close();
这种方式控制精细,但每个类都要手动实现,维护成本高。
2. 使用Boost.Serialization库
Boost.Serialization 是一个功能强大且广泛使用的C++序列化库,支持二进制、文本、XML等多种格式。
首先包含头文件并声明序列化接口:
#include#include class Person { private: friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { ar & name; ar & age; } public: std::string name; int age; Person() = default; Person(const std::string& n, int a) : name(n), age(a) {} };
然后使用不同的存档类型进行序列化:
#include#include // 序列化 { std::ofstream ofs("person.txt"); boost::archive::text_oarchive oa(ofs); Person p("Bob", 30); oa << p; } // 反序列化 { std::ifstream ifs("person.txt"); boost::archive::text_iarchive ia(ifs); Person p; ia >> p; }
Boost支持版本控制、指针、STL容器等复杂场景,适合大型项目。
3. 使用JSON库(如nlohmann/json)
对于需要可读性和跨平台交互的场景,JSON是不错的选择。以 nlohmann/json 为例:
#includeNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Person, name, age) // 序列化 nlohmann::json j = person; std::string json_str = j.dump(); // 反序列化 Person p = j.get ();
只需一行宏即可为简单结构体启用JSON序列化,适合配置、网络通信等场景。
4. Google Protocol Buffers(Protobuf)
Protobuf 是一种高效的二进制序列化格式,需先定义.proto文件:
message Person {
string name = 1;
int32 age = 2;
}
用protoc编译生成C++类,然后调用SerializeToString和ParseFromString即可完成序列化。
优点是性能高、体积小、跨语言,适合高性能服务间通信。
基本上就这些常见方式。选择哪种方法取决于你的需求:调试用JSON,性能关键用Protobuf或Boost,轻量场景可手写。关键是确保对象状态完整保存与恢复,注意字节序、版本兼容等问题。











