C++对象序列化方法包括手写函数、Boost.Serialization、JSON库(如nlohmann/json)和Protocol Buffers;选择依据性能、跨语言、开发效率等需求。

C++对象序列化,简单来说,就是把内存里的对象变成一串字节,方便存到文件里或者通过网络传输。反序列化就是反过来,把字节串变回对象。这俩操作在持久化数据、RPC(远程过程调用)啥的场景里特别有用。
把C++对象变成一串可以存储或传输的字节流,然后再变回来。
其实方法挺多的,各有优缺点。
自己手写序列化/反序列化函数: 这是最原始的方法,给每个类都写
serialize()
deserialize()
立即学习“C++免费学习笔记(深入)”;
class MyClass {
public:
int x;
std::string s;
void serialize(std::ostream& os) const {
os.write(reinterpret_cast<const char*>(&x), sizeof(x));
size_t len = s.size();
os.write(reinterpret_cast<const char*>(&len), sizeof(len));
os.write(s.data(), len);
}
void deserialize(std::istream& is) {
is.read(reinterpret_cast<char*>(&x), sizeof(x));
size_t len;
is.read(reinterpret_cast<char*>(&len), sizeof(len));
s.resize(len);
is.read(s.data(), len);
}
};这种方法需要自己处理字节对齐、大小端转换等问题。
使用第三方库,比如 Boost.Serialization: Boost 库功能强大,
Boost.Serialization
#include <boost/serialization/serialization.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <fstream>
class MyClass {
public:
int x;
std::string s;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & x;
ar & s;
}
};
int main() {
MyClass obj{10, "hello"};
std::ofstream ofs("data.txt");
boost::archive::text_oarchive ar(ofs);
ar & obj; // 序列化
MyClass obj2;
std::ifstream ifs("data.txt");
boost::archive::text_iarchive iar(ifs);
iar & obj2; // 反序列化
return 0;
}Boost.Serialization 支持多种序列化格式,例如文本、二进制和 XML。
使用 JSON 库,比如 nlohmann/json: 如果你的对象结构比较简单,或者需要和其他语言交互,用 JSON 序列化是个不错的选择。
nlohmann/json
#include <nlohmann/json.hpp>
#include <fstream>
using json = nlohmann::json;
class MyClass {
public:
int x;
std::string s;
json to_json() const {
json j;
j["x"] = x;
j["s"] = s;
return j;
}
void from_json(const json& j) {
x = j["x"];
s = j["s"];
}
};
int main() {
MyClass obj{10, "hello"};
json j = obj.to_json();
std::ofstream ofs("data.json");
ofs << j.dump(4); // 序列化成 JSON 字符串
MyClass obj2;
std::ifstream ifs("data.json");
json j2;
ifs >> j2;
obj2.from_json(j2); // 从 JSON 字符串反序列化
return 0;
}这种方法可读性好,易于调试,但性能相对较低。
Protocol Buffers (protobuf): 这是 Google 开发的一种数据序列化协议,特点是高效、跨语言。需要先定义
.proto
syntax = "proto3";
message MyClass {
int32 x = 1;
string s = 2;
}然后用
protoc
选择哪个方法,主要看你的需求。
总而言之,C++ 对象序列化是个挺有意思的话题,选择合适的方法并注意一些细节,就能让你的程序更健壮、更高效。
以上就是c++++如何将对象序列化_c++对象序列化与反序列化技术的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号