[英]C++ ifstream pointer open files fails
似乎ifstream*->open
无法按我预期的那样工作...这是代码:(在MAC OSX 10.7
使用-std=c++11
用g++ 4.7
编译)
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, char** argv)
{
string line;
vector<string> fname = {"a.txt","b.txt"};
vector<ifstream*> files ( 2, new ifstream );
files[0]->open( fname[0] );
getline( *files[0], line, '\n');
cerr<<"a.txt: "<<line<<endl;
//this one prints the first line of a.txt
line.clear();
files[1]->open( fname[1] );
getline( *files[1], line, '\n');
cerr<<"b.txt: "<<line<<endl;
//but this one fails to print any from b.txt
//actually, b.txt is not opened!
return 0;
}
谁能告诉我这是怎么回事???
这会在使用一次时执行一次new std::ifstream
,而不是您请求的每2
值一次。
new std::ifstream
创建一个ifstream指针,该指针的值由std::ifstream
构造函数在files
插入两次。
std::vector
仅处理其包含的对象,在这种情况下为ifstream*
指针。 因此, 2
复制指针值。 当files
超出范围时,将照顾指针(以及向量中的支持数据),但不会照顾指针所指向的值。 因此,vector不会删除新的std::ifstream
对象(在向量中放置了两次)。
不会为您调用operator delete
,因为指针可以有许多用途,而这些用途很难确定。 一种是故意将相同的指针两次放入向量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.