将fwrite()与类一起使用会发生什么? [英] What happens when you use fwrite() with a class?

查看:108
本文介绍了将fwrite()与类一起使用会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下内容:

class dataClass {
public:
    int someData;
    float moreData;
    void setData();
};
dataClass data;


如果我调用 fwrite(& data,sizeof(data),1, outputFilePointer); ?代码会像 dataClass 没有函数一样工作,还是我必须为每个成员调用 fwrite()

What would happen if I called fwrite(&data, sizeof(data), 1, outputFilePointer);? Would the code act as if dataClass had no functions, or would I have to call fwrite() with each member?

推荐答案

在这种情况下,您的类是POD,因此它的工作原理与使用Plain Old C时完全一样struct,即它将 data 的内存表示形式转储到磁盘上(包括编译器可能插入的填充字节)。

In this very case, your class is POD, so it would work exactly as it would if it was a Plain Old C struct, i.e. it will dump the memory representation of data on disk (including the padding bytes that the compiler may insert).

但是,如果 virtual 方法, virtual 继承和其他C ++东西开始使用,您可能会开始感到奇怪东西(您不仅会看到普通的数据字段,还会看到指向vtable的指针,也许还会看到编译器自动放入的其他东西);我认为多重继承也可能会增加混乱。

However, if virtual methods, virtual inheritance and other C++ stuff kicks in, you may start to see strange stuff (you will see not only your normal data fields, but also the pointer to the vtable and maybe other stuff put in automatically by the compiler); I think that also multiple inheritance may add confusion.

但是请注意,仅在对象上调用 fwrite 应该是无害的。在每种情况下(尽管这可能是未指定的行为,但我没有检查);相反,如果您尝试仅使用 fread 从文件反序列化非POD对象,则可能会出现问题(例如,正确的vtable指针可能会被存储在其中的那个指针覆盖)文件,该文件可能不再有效,这将使所有内容在下一次虚拟调用时崩溃。

Notice however that just calling fwrite on an object should be harmless in every case (although it may be unspecified behavior, but I didn't check); problems instead may arise if you instead try to deserialize a non-POD object from file with just an fread (for example, the correct vtable pointer may be overwritten by the one stored in the file, that can be no longer valid, and this will make everything blow up at the next virtual call).

这篇关于将fwrite()与类一起使用会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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