它似乎不像ifstream*->open我预期的那样工作......这是代码:( g++ 4.7使用-std=c++11in 编译MAC OSX 10.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;
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我这里有什么问题?
这将new std::ifstream在使用时执行一次,而不是每个2您请求的值执行一次.
在new std::ifstream创建一个ifstream的指针其指针值被插入两次在files由std::ifstream构造函数.
std::vector仅处理它包含的对象,在这种情况下是ifstream*指针.因此,2复制指针值.当files超出范围时,指针(以及向量中的支持数据)将被处理,但不是指针指向的值.因此,vector不会删除您的新std::ifstream对象(放置在向量中两次).
operator delete没有为你调用,因为指针可以有很多用途,无法轻易确定.其中一个是故意将相同的指针放在向量中两次.