我有像这个 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的拷贝构造函数吗?
最佳答案
std::string
在内部持有一个指针,指向在堆上分配的实际字符串数据。
write(char*, size_t)
AT ALL 不考虑内部类型(和关联的复制构造函数)。这意味着您正在编写一个指向文件的指针,但它永远不会起作用。
要正确修复它,您需要实际序列化以正确写出字符串(例如写入长度,然后是数据)
关于c++ - 如何在 C++ 中使用对象序列化保存和加载 std::string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23176758/