如何在 C++ 中保存和加载带有对象序列化的 std::string? [英] How do I save and load a std::string with object serialization in C++?

查看:114
本文介绍了如何在 C++ 中保存和加载带有对象序列化的 std::string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些简单的像这样的 POD 结构......

I had something simple like this POD structure...

struct Actor
{
    string name; 
    int hp;
};

稍后,为了简单起见,我使用...将结构保存到文件中

Later on, for simplicity sake here, I saved the structure to file using...

 ofstream_obj.write((char *)&PC, sizeof(Actor));

然后,我尝试读回文件.它加载了数据,但在退出时给出了一个丑陋的异常,指向 xutility 行: *_Pnext != 0

Then, I tried reading the file back. It loaded in the data, but upon exit it gave an ugly exception, pointing at xutility at the line of: *_Pnext != 0

inline void _Container_base12::_Orphan_all()
    {   // orphan all iterators
 #if _ITERATOR_DEBUG_LEVEL == 2
    if (_Myproxy != 0)
        {   // proxy allocated, drain it
        _Lockit _Lock(_LOCK_DEBUG);

        for (_Iterator_base12 **_Pnext = &_Myproxy->_Myfirstiter;
            *_Pnext != 0; *_Pnext = (*_Pnext)->_Mynextiter)
            (*_Pnext)->_Myproxy = 0;
        _Myproxy->_Myfirstiter = 0;
        }
 #endif /* _ITERATOR_DEBUG_LEVEL == 2 */
    }

放弃后,我将 std::string 更改为 char name[20],再次尝试整个过程,效果很好.加载 std::string 有什么不同吗?不是调用std::string的拷贝构造函数吗?

After giving up, I changed the std::string to char name[20], tried the whole thing again, and it worked fine. Is there something different about loading back std::string? Is it not calling std::string's copy constructor?

推荐答案

std::string 在内部保存了一个指向在堆上 malloc 的实际字符串数据的指针.

std::string holds a pointer internally to the actual string data which is malloced on the heap.

write(char*, size_t) 不考虑内部类型(和关联的复制构造函数)完全.这意味着您正在写入一个指向文件的指针,但它永远不会起作用.

write(char*, size_t) doesn't consider internal types (and associated copy constructors) AT ALL. This means that you were writing a pointer to a file, which never works.

要正确修复它,您需要实际序列化以正确写出字符串(例如写入长度然后是数据)

to fix it properly you would need actual serialization that writes the string out properly (like write length and then the data)

这篇关于如何在 C++ 中保存和加载带有对象序列化的 std::string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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