C++ Access Violation while Reading from File

元气小坏坏 提交于 2019-12-08 04:26:18

问题


Just starting out on C++.

I am getting access violation errors while reading from a binary file. Here are the classes involved:

class Staff { //base class
public:
    Staff() {}
    virtual ~Staff{}
}

One of the derived classes:

class Scheduler : public Staff {
public:
    Scheduler() {}
    //no destructor defined
}

And then in code that uses these classes:

ifstream in("Scheduler.dat", ios::in | ios::binary);
Scheduler s;
in.read(reinterpret_cast<char *>(&s), sizeof(Scheduler));

The moment I hit the read statement, the access violation exception triggers, and VS2013 points to the virtual destructor in class Staff.

Is it because I didn't explicitly create a destructor in class Scheduler? Or is it caused by something else?


回答1:


Scheduler is not a trivially copyable class, you cannot read from or write it bytewise to a file like this.

http://en.cppreference.com/w/cpp/types/is_trivially_copyable

A trivially copyable class is a class that

  1. Has no non-trivial copy constructors (this also requires no virtual functions or virtual bases)
  2. Has no non-trivial move constructors
  3. Has no non-trivial copy assignment operators
  4. Has no non-trivial move assignment operators
  5. Has a trivial destructor

You'll either have to remove the virtual destructor (which brings its own set of issues if you want to use Staff polymorphically), read and write to the file using a serialization library, or write your own serialization function, the canonical way would be something like std::ostream& operator<<(std::ostream&, Staff const&);



来源:https://stackoverflow.com/questions/26605536/c-access-violation-while-reading-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!