如何在C++中使用boost库序列化自定义class ?| serialize and deserialize a class in cpp with boost

本文介绍了如何在C++中使用boost库进行序列化和反序列化操作,包括字符串的序列化、通过ostream/istream的方法、boost的text、xml和binary档案格式。同时,文章探讨了std::string的注意事项,以及boost的侵入式和非侵入式序列化风格,并展示了shared_ptr的处理方式。
摘要由CSDN通过智能技术生成

本文首发于个人博客https://kezunlin.me/post/6887a6ee/,欢迎阅读!

serialize and deserialize a class in cpp

Guide

how to serialize string

size data

The easiest serialization method for strings or other blobs with variable size is to serialize first the size as you serialize integers, then just copy the content to the output stream.

When reading you first read the size, then allocate the string and then fill it by reading the correct number of bytes from the stream.

with ostream/istream

native way with ostream/istream for example class MyClass with height,width,name fields.

class MyClass {
   
public:
	int height;
   int width;
   std::string name;
}

std::ostream& MyClass::serialize(std::ostream &out) const {
   
    out << height;
    out << ',' //number seperator
    out << width;
    out << ',' //number seperator
    out << name.size(); //serialize size of string
    out << ',' //number seperator
    out << name; //serialize characters of string
    return out;
}
std::istream& MyClass::deserialize(std::istream &in) {
   
    if (in) {
   
        int len=0;
        char comma;
        in >> height;
        in >> comma; //read in the seperator
        in >> width;
        in >> comma; //read in the seperator
        in >> len;  //deserialize size of string
        in >> comma; //read in the seperator
        if (in && len) {
   
            std::vector<char> tmp(len);
            in.read(tmp.data() , len); //deserialize characters of string
            name.assign(tmp.data(), len);
        }
    }
    return in;
}

overload for operator<< and operator>>

std::ostream& operator<<(std::ostream& out, const MyClass &obj)
{
   
    obj.serialize(out)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值