Flow Pointers Vector

Here is my problem, I need to create X number of files and write them depending on different facts, my solution was to create a vector of stream pointers, like this

#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());
          }

Before this part, it creates files perfectly, and later in the program I write to them, which is also great, my problem is when I want to close objects, if I use:

for(i=0;i<SplitVec.size()-4;i++)
          {
              *files[i].close();
          }

I get the following error:

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*'

So, I have a question, firstly, why I can’t call close, its a pointer to the stream, so with * files [i] I would suggest that I can close it, and secondly, if I do not close it works fine but I’m pretty sure that this is bad practice, and I don’t want to be a lazy or shitty programmer, I looked as I could, but I did not find the answer. Thank!

+5
2

(, , , ) ).

++ RAII.

, shared_ptr ( Boost ++ 11 <memory>), vector shared_ptr 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() .

( ++ 11 move-semantics-powered unique_ptr a vector<unique_ptr<ofstream>>, , , make_shared unique_ptr, , make_unique, , Herb Sutter.)

, files[i]->close() .

+5

(*files[i]).close();

files[i]->close();
+9

All Articles