c++ - 二进制文件的模板化读写

标签 c++ templates serialization fstream

所以,我一直在尝试通过以下方式在 C++ 中自动读取和写入二进制文件(基本上,因为在处理动态数据时,事情变得具体):

#include <iostream>
#include <fstream>
using namespace std;

template <class Type>
void writeinto (ostream& os, const Type& obj) {
    os.write((char*)obj, sizeof(Type));
}

template <class Type>
void readfrom (istream& is, const Type& obj) {
    is.read((char*)obj, sizeof(Type));
}

int main() {
    int n = 1;
    int x;

    fstream test ("test.~ath", ios::binary | ios::out | ios::trunc);
    writeinto(test, n);
    test.close();

    test.open("test.~ath", ios::binary | ios::in);
    readfrom(test, x);
    test.close();

    cout << x;
}

预期输出为“1”;但是,此应用程序在屏幕上显示任何内容之前就崩溃了。更具体地说,就在 writeinto 函数内部。

我可以解释原因吗?如果可能的话,可以提供解决方案吗?

最佳答案

您需要获取对象的地址:

#include <memory>

os.write(reinterpret_cast<char const *>(std::addressof(obj)), sizeof(Type));
//                                      ^^^^^^^^^^^^^^^^^^^

在紧急情况下,您也可以说 &obj,但在存在重载的 operator& 时这并不安全。

关于c++ - 二进制文件的模板化读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13215856/

相关文章:

java - 序列化 ClassPathXmlApplicationContext

mysql - 数据非规范化和C#对象数据库序列化

c++ - C 或 C++ websocket 客户端工作示例

C++ 错误 : no matching function for all to

c++ - 我如何使用和专门化 'curious repeating template pattern'

c++ - 使用 C++ 模板函数递归编译时间

c# - 在动态程序集中序列化类

c++ - 函数 C++ 中的动态分配

c++ - 使用 Boost 从 C++ 中的样本 vector 计算平均值和标准差

c++ - 如何推断模板使用的 std::bind 对象的返回类型?