在 C++ 中将 Class(带有 Vector 成员)保存为二进制文件
Saving a Class (with Vector member) as Binary File in C++
我正在尝试使用二进制文件保存和加载 class Student
。 classes 是这样的:
class Student{
char name[100];
int regno;
vector<Subjects> subjects;
};
class Subjects{
char initial;
int id;
};
我是这样保存和加载的:
void saveFile(){
fstream f1;
f1.open("data.bin", ios::out | ios::binary);
f1.write((char*)&student, sizeof(Student));
f1.close();
}
void loadFile(){
fstream f1;
f1.open("data.bin", ios::in | ios::binary);
f1.read((char*)&student, sizeof(Student));
f1.close();
}
保存和加载没有什么特别之处,但我通过打印语句对此进行了测试,它是矢量组件,当 运行 它在终端 (cmd.exe)
中时导致崩溃。
除非在将 Student
对象保存到文件之前对其进行序列化,否则不能简单地保存和加载对象。
依据:
class Student
不是 POD 类型。 std::vector<Subjects>
在你的 Student
class 中只包含一个指向包含 Subjects
的底层内存的指针,因为 vector
使用堆来保存其内容。将对象保存到文件时,只需将指针与 Student
对象一起保存,而不是实际数据。因此,当您尝试从保存的二进制数据中重新创建相同的对象时,您只能访问内存地址而不是实际内容。
在 C++ 世界中,boost::serialization
、Protocol buffers
和 cereal
是最知名的(但不限于)序列化库来实现什么你正在尝试做。
std::vector
不是 POD type。
std::vector
分配动态内存并在内部某处存储指针。当你将它写入文件时,你只需将 header 写入该动态内存,即 std::vector
。当你再次读取它时,它不再是一个有效的指针,你会崩溃。
我正在尝试使用二进制文件保存和加载 class Student
。 classes 是这样的:
class Student{
char name[100];
int regno;
vector<Subjects> subjects;
};
class Subjects{
char initial;
int id;
};
我是这样保存和加载的:
void saveFile(){
fstream f1;
f1.open("data.bin", ios::out | ios::binary);
f1.write((char*)&student, sizeof(Student));
f1.close();
}
void loadFile(){
fstream f1;
f1.open("data.bin", ios::in | ios::binary);
f1.read((char*)&student, sizeof(Student));
f1.close();
}
保存和加载没有什么特别之处,但我通过打印语句对此进行了测试,它是矢量组件,当 运行 它在终端 (cmd.exe)
中时导致崩溃。
除非在将 Student
对象保存到文件之前对其进行序列化,否则不能简单地保存和加载对象。
依据:
class Student
不是 POD 类型。 std::vector<Subjects>
在你的 Student
class 中只包含一个指向包含 Subjects
的底层内存的指针,因为 vector
使用堆来保存其内容。将对象保存到文件时,只需将指针与 Student
对象一起保存,而不是实际数据。因此,当您尝试从保存的二进制数据中重新创建相同的对象时,您只能访问内存地址而不是实际内容。
在 C++ 世界中,boost::serialization
、Protocol buffers
和 cereal
是最知名的(但不限于)序列化库来实现什么你正在尝试做。
std::vector
不是 POD type。
std::vector
分配动态内存并在内部某处存储指针。当你将它写入文件时,你只需将 header 写入该动态内存,即 std::vector
。当你再次读取它时,它不再是一个有效的指针,你会崩溃。