从文件读取时C ++访问冲突 [英] C++ Access Violation while Reading from File

查看:505
本文介绍了从文件读取时C ++访问冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始使用C ++。



我从二进制文件读取时遇到访问冲突错误。这里是涉及的类:

  class Staff {//基类
public:
Staff {}
virtual〜Staff {}
}

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

然后在使用这些类的代码中:

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

当我点击read语句时,访问冲突异常触发器,VS2013指向虚拟析构函数在职员。



是因为我没有在类Scheduler中显式创建析构函数?或者是其他原因造成的?

解决方案

调度程序



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


一个简单的可复制类是


  1. 没有非平凡的复制构造函数虚拟函数或虚拟基础)

  2. 没有非平凡的移动构造函数

  3. 没有非平凡的副本赋值运算符

  4. 没有非平凡的移动赋值运算符

  5. 有一个简单的析构函数




你必须删除虚拟析构函数(如果你想使用 Staff ),使用序列化库读取和写入文件,或者编写自己的序列化函数,规范的方式将是类似 std :: ostream& operator<<<(std :: ostream& Staff const&);


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?

解决方案

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&);

这篇关于从文件读取时C ++访问冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆