这就是我的问题,我需要创建X个文件,并根据不同的因素写入它们,我的解决方案是创建一个这样的ofstream指针矢量
#include <boost/algorithm/string.hpp>
#include <vector>
#include<string>
#include <iostream>
#include <fstream>
vector<ofstream*> files;
files.resize(SplitVec.size()-4);
for(i=0;i<SplitVec.size()-4;i++)
{
line="/Users/jorge/Desktop/testing/strain_"+lexical_cast<string>(i);
cout<<"ine"<<endl;
files[i]=new ofstream(line.c_str());
}直到这一部分,它创建了很棒的文件,后来在程序中我写给它们,这也很棒,我的问题是当我想要关闭对象时,如果我使用:
for(i=0;i<SplitVec.size()-4;i++)
{
*files[i].close();
}我得到以下错误:
In file included from main.cpp:14:./methyl.h:298: error: request for member 'close' in 'files. std::vector<_Tp, _Alloc>::operator[] [with _Tp = std::ofstream*, _Alloc = std::allocator<std::ofstream*>](1ul)', which is of non-class type 'std::ofstream*'所以,我有一个问题,首先,为什么我不能调用close,它是一个指向ofstream的指针,所以使用*filesi,我会想象我可以关闭它,其次,如果我不关闭它,程序运行正常,但我几乎可以肯定这是一个糟糕的做法,我不想成为一个懒惰或糟糕的程序员,我已经尽可能地寻找了,但我找不到答案。谢谢!
发布于 2012-09-20 17:58:34
你的代码不是异常安全的(例如,如果抛出一个异常,因为你有一个原始指针的向量,它们是带有相关流句柄的泄漏的)。
我建议使用一种现代的C++ RAII方法。
例如,如果您使用像shared_ptr (从Boost或从C++11 <memory> header)这样的智能指针,则可以构建一个shared_ptr的vector,并使用make_shared来分配ofstream对象:
// RAII exception-safe approach
vector<shared_ptr<ofstream>> files;
// Add a new ofstream object to the vector:
files.push_back( make_shared<ofstream>( filename ) );当向量超出作用域时,它会被析构,所有指向的流对象都会自动释放:非常简单、清晰且异常安全。
如果你想在向量超出作用域之前强制进行流清理,你可以只在向量上调用.clear()方法。
(另一种选择是使用C++11移动语义驱动的unique_ptr,并定义一个vector<unique_ptr<ofstream>>,但不幸的是,没有用于unique_ptr的make_shared的标准等价物,并且代码可能会更冗长,除非您编写make_unique的自定义实现,如the one proposed by Herb Sutter。)
注意,通常的files[i]->close()语法也适用于智能指针向量的这种情况。
发布于 2012-09-20 17:32:57
使用
(*files[i]).close();或直接
files[i]->close();https://stackoverflow.com/questions/12509799
复制相似问题