//这是测试用的类
class A {
public:
int _i;
string _str;
vector<int> _vec;
A(const int i = 0, const string str = "hi", vector<int> vec = { 0 })
:_a(i), _b(str), _vec(vec) {}
};
//这是第一次测试,输出是正确的
int main()
{
A a(1, "hello", { 1,2,3 });
ofstream out("test.txt", ios::binary);
out.write((char*)&a, sizeof(a));
out.close();
A b;
ifstream in("test.txt", ios::binary);
in.read((char*)&b, sizeof(b));
in.close();
cout << b._i << b._str << *b._vec.begin();
getchar();
}
//然后我把写入文件的部分注释掉了,程序就不能用了
int main()
{
/*A a(1, "hello", { 1,2,3 });
ofstream out("test.txt", ios::binary);
out.write((char*)&a, sizeof(a));
out.close();*/
A b;
ifstream in("test.txt", ios::binary);
in.read((char*)&b, sizeof(b));
in.close();
cout << b._i << b._str << *b._vec.begin();
getchar();
}
Only POD without pointers can write the entire struct directly into the file. This is like being fooled by junk textbooks. The same goes for our textbooks back then.
Because string and vector contain pointers to the heap area.
Every time the program runs, it is not necessarily allocated to one place. What you read next time is junk data.
You should find a way to save its actual data, find a json library or something.
What you save is a reference to the object. The data on the stack is stored, but the data on the heap is not.
Different string implementations may result in inconsistent sizes of class objects
It may sound confusing
There is no problem in saving basic data types, but
string
andvector
cannot. Otherwise, you can implement one yourself, like c