【发布时间】:2015-05-11 08:23:45
【问题描述】:
我正在尝试序列化和反序列化包含向量的对象 使用 ofstream 和 ifstream。序列化过程就像一个魅力,但只要我调用 ifstream 的 read 方法,我就会得到一个双重释放或损坏异常。这是我的代码:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class A
{
private:
vector<int> v;
public:
void add(int e) {
v.push_back(e);
}
void print() {
vector<int>::iterator it;
cout << "[" << v.at(0);
for(it = v.begin()+1; it!=v.end(); ++it)
cout << "," << *it;
cout << "]" << endl;
}
};
int main()
{
A a;
A s;
ofstream ofs;
ifstream ifs;
for (int i=1; i<= 10; i++)
a.add(i);
a.print();
ofs.open("s.bin", ios::binary);
ofs.write((char *) &a, sizeof(a));
ofs.close();
ifs.open("s.bin", ios::binary);
ifs.read((char *) &s, sizeof(s));
ifs.close();
cout << "s: ";
s.print();
return 0;
}
一个奇怪的行为是,程序打印出反序列化的对象。这是我的输出:
[1,2,3,4,5,6,7,8,9,10]
s: [1,2,3,4,5,6,7,8,9,10]
*** Error in `./a.out': double free or corruption (fasttop): 0x000000000187c080 ***
任何想法是什么导致了这个问题?我一无所知。
【问题讨论】:
-
最终的原因是您没有序列化对象,而只是将其在内存中的表示写入磁盘。
-
@molbdnilo 感谢您的提示。我会看看 Tony 在接受的答案中提到的 boost 库。
标签: c++ serialization