【问题标题】:How do I save and load a std::string with object serialization in C++?如何在 C++ 中使用对象序列化保存和加载 std::string?
【发布时间】:2014-04-19 00:08:23
【问题描述】:

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

struct Actor
{
    string name; 
    int hp;
};

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

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

然后,我尝试读回文件。它加载了数据,但在退出时它给出了一个丑陋的异常,指向 xutility 的行: *_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的拷贝构造函数?

【问题讨论】:

    标签: c++ serialization


    【解决方案1】:

    std::string 在内部保存一个指向实际字符串数据的指针,该数据被分配在堆上。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 2011-04-30
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      相关资源
      最近更新 更多