序列化包含std :: string的类 [英] Serializing a class which contains a std::string

查看:195
本文介绍了序列化包含std :: string的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是一个c ++专家,但我已经把事情序列化过去几次。不幸的是,这次我试图序列化一个类,它包含一个std :: string,我的理解是很像序列化一个指针。

I'm not a c++ expert but I've serialized things a couple of times in the past. Unfortunately this time I'm trying to serialize a class which contains a std::string, which I understand is pretty much like serializing a pointer.

我可以写出类复制到文件并重新读取。所有int字段都很好,但std :: string字段给出了一个地址超出范围错误,可能是因为它指向不再存在的数据。

I can write out the class to a file and read it back in again. All int fields are fine but the std::string field gives an "address out of bounds" error, presumably because it points to data which is no longer there.

有标准的解决方法吗?我不想回到char数组,但至少我知道他们在这种情况下工作。我可以提供代码,如果必要,但我希望我已解释我的问题很好。

Is there a standard workaround for this? I don't want to go back to char arrays but at least I know they work in this situation. I can provide code if necessary but I'm hoping I've explained my problem well.

我通过将类转换为char *一个文件与fstream。

I'm serializing by casting the class to a char* and writing it to a file with fstream. Reading of course is just the reverse.

推荐答案


我通过将类转换为char *并将其写入带有fstream的
文件。当然只是相反的。

I'm serializing by casting the class to a char* and writing it to a file with fstream. Reading of course is just the reverse.

不幸的是,只有没有涉及指针,这才有效。你可能想给你的类 void MyClass :: serialize(std :: ostream) void MyClass :: deserialize(std :: ifstream) / code>,并调用那些。对于这种情况,您需要

Unfortunately, this only works as long as there are no pointers involved. You might want to give your classes void MyClass::serialize(std::ostream) and void MyClass::deserialize(std::ifstream), and call those. For this case, you'd want

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;
}

您还可能希望重载流运算符以方便使用。

You may also want to overload the stream operators for easier use.

std::ostream &operator<<(std::ostream& out, const MyClass &obj)
{obj.serialize(out); return out;}
std::istream &operator>>(std::istream& in, MyClass &obj)
{obj.deserialize(in); return in;}

这篇关于序列化包含std :: string的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆