c ++:关闭控制台应用程序后出现异常错误

c++: exception error after closing console app

我正在学习c++,有一个关于读写对象到文件的问题。

我创建了一个名为 Person 的 class。在我的主文件中,我创建了 Person class 的两个实例。我将实例一写入名为 "person.dat" 的文件,然后将其读回我创建的第二个实例。一切都按预期工作,除了在程序关闭后抛出异常。我不确定原因或原因。

Exception: Unhandled exception at 0x55ABDF62 (msvcp120d.dll) in Writing Binary Objects.exe: 0xC0000005: Access violation writing location 0xFEEEFEEE.

任何人都可以帮我解释一下吗?

代码:Person.h

#include <iostream>
#include <string>

using namespace std;

class Person {
    private:
        string name;
        string surname;
        int age;
    public:
        Person();
        Person(string, string, int);
        void setName(string);
        void setSurname(string);
        void setAge(int);
        string getName();
        string getSurname();
        int getAge();
};

Person::Person() {}

Person::Person(string _name, string _surname, int _age) {
    setName(_name);
    setSurname(_surname);
    setAge(_age);
}

void Person::setName(string _name) {
    name = _name;
}

void Person::setSurname(string _surname) {
    surname = _surname;
}

void Person::setAge(int _age) {
    age = _age;
}

string Person::getName() {
    return name;
}

string Person::getSurname() {
    return surname;
}

int Person::getAge() {
    return age;
} 

代码:Program.cpp

#include <iostream>
#include <fstream>

#include "Person.h"

using namespace std;

int main() {

    //create person 1
    Person person;
    person.setName("Kobus");
    person.setSurname("Beets");
    person.setAge(24);

    //write person 1 to file
    ofstream out;
    out.open("person.dat", ios::binary);    
    out.write(reinterpret_cast <char *> (&person), sizeof(person));
    out.close();    

    //create person 2
    Person person2;
    person2.setName("John");
    person2.setSurname("Doe");
    person2.setAge(26);    

    //read person 1 from file into person 2
    ifstream in;
    in.open("person.dat", ios::binary);
    in.read(reinterpret_cast <char *> (&person2), sizeof(person2));
    in.close();

    //print new person 2
    cout << " " << person2.getName() << " " << person2.getSurname() << " is " << person2.getAge() << " year(s) old... \n\n ";

    system("pause");

    return 0;
}

你不能以这种方式直接将对象写入文件,除非你有 POD 风格的数据结构(例如,只是简单的 C 数据类型或其中的 struct/class,没有指针,没有 C++ 数据类型) .

在你的例子中,Person 有两个 std::string 成员,它们本身包含指针和其他东西,一旦写入文件并重新读取到内存,它们将失去其意义。

您需要添加更多逻辑来编写实际的字符串内容(参见 std::string::c_str()、std::string::data()、std::string::size()).

异常可能是由 std::string 析构函数引起的,它试图释放或访问已经释放的内存。