从文件读取时出现 C++ 访问冲突

标签 c++ file binary destructor

刚开始使用 C++。

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

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

派生类之一:

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

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

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

在我点击读取语句的那一刻,访问冲突异常触发,VS2013 指向类 Staff 中的虚拟析构函数。

是不是因为我没有在Scheduler类中显式创建析构函数?还是其他原因引起的?

最佳答案

Scheduler不是简单可复制的类,您不能像这样按字节读取或写入文件。

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

您要么必须删除虚拟析构函数(如果您想以多态方式使用 Staff,它会带来一系列问题),使用序列化库读取和写入文件,或者编写您自己的序列化函数,规范的方式类似于 std::ostream& operator<<(std::ostream&, Staff const&);

关于从文件读取时出现 C++ 访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26605536/

相关文章:

java - 提高字符串到二进制数转换的性能

c# - LINQ to Entities - 更新二进制字段

c++ - 如何将宏用作其他宏参数列表之一

C++ 指针容器

perl - 在 Perl 中,我可以将字符串视为字节数组吗?

c++ - 在一个解决方案中使用多个 .cpp 文件的目的是什么?

c - 从c中的文件中读取带空格的字符串

c++ - 高精度计算平均值的最佳策略

c++ - 编写决策树并将其加载到文件 C++

c - 在C中通过套接字发送二进制文件(从Windows到Linux)