【发布时间】:2010-03-18 11:51:53
【问题描述】:
对于一些图形工作,我需要尽快读取大量数据,并且理想情况下希望直接读取数据结构并将其写入磁盘。基本上我有各种文件格式的 3d 模型,加载时间太长,所以我想把它们写成“准备好的”格式作为缓存,这样在程序的后续运行中加载速度会更快。
这样做安全吗? 我担心的是直接读入向量的数据?我已经删除了错误检查,将 4 硬编码为 int 的大小等等,这样我就可以给出一个简短的工作示例,我知道这是不好的代码,我的问题真的是在 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,在制作 cmets 之前尽量避免不阅读问题;)
-
@Poita_ :) 我知道更改仅用于压缩,但事实是
4仅比sizeof(int)略小,并且应该始终首选后者,即使在合成代码sn-ps。 -
@David 确实如此。我真的同意,我只是对我的样本很懒
-
10k 人看了,只有 8 人对接受的答案投了赞成票?