C++从 ifstream 读取():没有指针?
假设我有一个结构体和一个包含这些结构体的二进制表示形式的文件,我将创建一个使用 ifstream::read() 访问此二进制数据的函数/方法。
这是一个示例结构:
struct MyStruct {
int x; //Value interested in
int y; //Value interested in
int anotherInteger; //Not interested
double aDouble; //Not interested
}
我如何制作该函数(我在这里称之为 readData):读取时不使用指针,或者如果需要使用指针,我将在哪里放置正确的删除?
到目前为止,我的 readData 的相关部分如下所示:
void readData(int position, int &returnX, int &returnY) {
ifstream inFile("binaryFile.dat",ios::binary);
MyStruct *st = new MyStruct[1];
inFile.seekg(sizeof(MyStruct)*pos);
inFile.read((char*) st, sizeof(MyStruct));
returnX = st[0].x;
returnY = st[0].y;
//delete [] st goes here?
}
我尝试取消注释删除部分,但出现分配错误,可能是因为 x 和 y 的值指向不再存在的内容。
关于如何解决这个问题有什么想法吗?
Suppose I have a struct and a file with binary representations of those structs and I'll make a function/method that access this binary data using ifstream::read()
.
Here's an example struct:
struct MyStruct {
int x; //Value interested in
int y; //Value interested in
int anotherInteger; //Not interested
double aDouble; //Not interested
}
How do I make the function (I'll call it here readData) either: not using pointers when reading or, if using pointers is necessary, where would I put the proper delete?
So far, the relevant part of my readData looks like this:
void readData(int position, int &returnX, int &returnY) {
ifstream inFile("binaryFile.dat",ios::binary);
MyStruct *st = new MyStruct[1];
inFile.seekg(sizeof(MyStruct)*pos);
inFile.read((char*) st, sizeof(MyStruct));
returnX = st[0].x;
returnY = st[0].y;
//delete [] st goes here?
}
I've tried uncommenting the delete part, but I get an allocation error, probably because the values of x and y are pointing to something that doesn't exist anymore.
Any ideas on how to solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不使用局部变量呢?
此外,参考文献不能重新定位。因此,赋值将值赋给调用函数传递的原始
int
。returnX
和returnY
不指向局部变量。在上面的代码中,赋值更改了mainx
和mainy
。Why wouldn't you use a local variable?
Also, references cannot be re-seated. Therefore the assignment assigns the value to the origional
int
passed by the calling function.returnX
andreturnY
are not pointed at the local variables. In the code above, the assignment changesmainx
andmainy
.更简单的方法是使用局部变量:
The simpler way it's to use a local variable:
delete[]
没问题。如果出现错误,这并不是因为 x 和 y 的值指向不再存在的东西,因为它们的值只是整数并且不指向任何东西。The
delete[]
is fine. If you get an error, it's not because the values of x and y are pointing to something that doesn't exist anymore since their values are just integers and don't point to anything.