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

在C++中,序列化是指将对象的状态转换为可以存储或传输的格式(如字节流、JSON、XML等),反序列化则是将其还原为原来的对象。由于C++标准库没有内置的序列化机制,实现序列化通常需要手动编写代码或借助第三方库。以下是几种常见的C++对象序列化方法。
最直接的方法是自己定义序列化逻辑,通过重载和>>操作符或提供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<const char*>(&name_len), sizeof(name_len));
out.write(name.c_str(), name_len);
out.write(reinterpret_cast<const char*>(&age), sizeof(age));
}
// 从输入流反序列化
void deserialize(std::istream& in) {
size_t name_len;
in.read(reinterpret_cast<char*>(&name_len), sizeof(name_len));
name.resize(name_len);
in.read(&name[0], name_len);
in.read(reinterpret_cast<char*>(&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();
这种方式控制精细,但每个类都要手动实现,维护成本高。
Boost.Serialization 是一个功能强大且广泛使用的C++序列化库,支持二进制、文本、XML等多种格式。
首先包含头文件并声明序列化接口:
#include <boost/serialization/string.hpp>
#include <boost/serialization/access.hpp>
class Person {
private:
friend class boost::serialization::access;
template<class Archive>
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 <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
// 序列化
{
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容器等复杂场景,适合大型项目。
对于需要可读性和跨平台交互的场景,JSON是不错的选择。以 nlohmann/json 为例:
#include <nlohmann/json.hpp> NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Person, name, age) // 序列化 nlohmann::json j = person; std::string json_str = j.dump(); // 反序列化 Person p = j.get<Person>();
只需一行宏即可为简单结构体启用JSON序列化,适合配置、网络通信等场景。
Protobuf 是一种高效的二进制序列化格式,需先定义.proto文件:
message Person {
string name = 1;
int32 age = 2;
}
用protoc编译生成C++类,然后调用SerializeToString和ParseFromString即可完成序列化。
优点是性能高、体积小、跨语言,适合高性能服务间通信。
基本上就这些常见方式。选择哪种方法取决于你的需求:调试用JSON,性能关键用Protobuf或Boost,轻量场景可手写。关键是确保对象状态完整保存与恢复,注意字节序、版本兼容等问题。
以上就是c++++如何序列化和反序列化一个对象 _c++对象序列化方法详解的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号