为了进行一些图形工作,我需要尽可能快地读入大量数据,并希望直接将数据结构读入和写入磁盘。基本上,我有许多不同文件格式的 3D 模型需要加载,这需要太长时间,因此我想将它们以其“准备好”的格式写出,作为缓存,在程序的后续运行中加载得更快。
这样做安全吗? 我的担心在于直接读取向量的数据?我已经删除了错误检查,硬编码了整数的大小等内容,以便提供一个简短的工作示例。我知道这是糟糕的代码,但我真正想问的问题是,像这样直接将整个结构体数组读入向量是否在 C++ 中是安全的?我相信是可以的,但是当你开始使用底层和直接处理原始内存时,C++ 会有很多陷阱和未定义的行为。
我意识到数字格式和大小可能会在平台和编译器之间发生改变,但这只会被同一编译器程序读取和写入,以缓存数据,以备稍后运行同一程序时可能需要。
#include <fstream>
#include <vector>
using namespace std;
struct Vertex
{
float x, y, z;
};
typedef vector<Vertex> VertexList;
int main()
{
// Create a list for testing
VertexList list;
Vertex v1 = {1.0f, 2.0f, 3.0f}; list.push_back(v1);
Vertex v2 = {2.0f, 100.0f, 3.0f}; list.push_back(v2);
Vertex v3 = {3.0f, 200.0f, 3.0f}; list.push_back(v3);
Vertex v4 = {4.0f, 300.0f, 3.0f}; list.push_back(v4);
// Write out a list to a disk file
ofstream os ("data.dat", ios::binary);
int size1 = list.size();
os.write((const char*)&size1, 4);
os.write((const char*)&list[0], size1 * sizeof(Vertex));
os.close();
// Read it back in
VertexList list2;
ifstream is("data.dat", ios::binary);
int size2;
is.read((char*)&size2, 4);
list2.resize(size2);
// Is it safe to read a whole array of structures directly into the vector?
is.read((char*)&list2[0], size2 * sizeof(Vertex));
}
os.write(&size1, sizeof(size1))
比在此处硬编码4更好。同样的,读取也是如此。 - David Rodríguez - dribeas4
只比sizeof(int)
稍小一点,后者应始终优先考虑,即使在合成的代码片段中也是如此。 - David Rodríguez - dribeas