为什么 interpret_cast 运算符在 cpp 中被认为是危险的?有更好的方法吗?

问题描述 投票:0回答:0

我正在研究 cpp 文件中的随机访问。我遇到了 reinterpret_cast 运算符。它允许您将指针从一种类型转换为另一种类型,即使这些类型之间没有任何关联。但是,据说这被认为是危险的,可能会产生意外结果和程序崩溃。我想了解为什么以及如何?

我写的代码:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    fstream file("example.txt", ios::out);
    if (!file)
    {
        cerr << "Failed to open file." << endl;
        return 1;
    }
    file.seekp(4 * sizeof(int), ios::beg);
    int newValue = 50;
    file.write(reinterpret_cast<const char *>(&newValue), sizeof(int));
    file.close();
    return 0;
}
c++ file file-handling reinterpret-cast
© www.soinside.com 2019 - 2024. All rights reserved.