C ++访问冲突,而从文件读取 [英] C++ Access Violation while Reading from File
问题描述
刚开始的C ++。
我收到访问冲突的错误,同时从二进制文件中读取。这里所涉及的类:
一流的工作人员{//基类
上市:
工作人员(){}
虚拟〜人员{}
}
一个派生类:
类计划:大众员工{
上市:
调度程序(){}
//没有析构函数定义
}
然后在code,使用这些类:
ifstream的中(Scheduler.dat的ios ::在| IOS ::二进制);
调度S;
in.read(reinter pret_cast<字符*>(安培; S)的sizeof(调度));
我打的读声明的那一刻,访问冲突异常触发和VS2013指向一流的工作人员的虚析构函数。
是不是因为我没有明确创建类调度析构函数?或者它被别的什么原因引起的?
计划
是不是一个平凡的可复制类,你无法读取或写入按字节像一个文件这一点。
HTTP://en.cp$p$pference.com/ W / CPP /类型/ is_trivially_copyable
一个平凡的可复制类是一类
- 已经没有非平凡的拷贝构造函数(这也需要没有虚函数或虚拟基)
- 已经没有了不平凡的举动构造
- 已经没有了不平凡的拷贝赋值运算符
- 已经没有了不平凡的举动赋值运算符
- 拥有平凡的析构函数
块引用>您要么必须删除虚拟析构函数,读取和使用写入文件(如果你想使用
员工
多态带来其自身的一系列问题)一个序列化库,或写自己的序列化功能,规范的方法会是这样的的std :: ostream的&放大器;运营商的LT;≤(的std :: ostream的和放大器;,员工常量和放大器;);
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
- Has no non-trivial copy constructors (this also requires no virtual functions or virtual bases)
- Has no non-trivial move constructors
- Has no non-trivial copy assignment operators
- Has no non-trivial move assignment operators
- 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 likestd::ostream& operator<<(std::ostream&, Staff const&);
这篇关于C ++访问冲突,而从文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!