Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading fstreams into a std::vector in c++

This is a simple and complex question at the same time.

This compiles:

int Test;
vector<int> TEST;
TEST.push_back(Test);
cout << TEST.size();

This does not compile:

fstream Test;
vector<fstream> TEST;
TEST.push_back(Test);
cout << TEST.size();

Is there any particular reason? Is there a way for me to get a dynamic list of fstreams?

The error message:

1>------ Build started: Project: vector_test, Configuration: Debug Win32 ------
1>  vector_test.cpp
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\fstream(1347): error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ios(176) : see declaration of 'std::basic_ios<_Elem,_Traits>::basic_ios'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          This diagnostic occurred in the compiler generated function 'std::basic_fstream<_Elem,_Traits>::basic_fstream(const std::basic_fstream<_Elem,_Traits> &)'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
like image 754
shieldfoss Avatar asked Mar 27 '12 12:03

shieldfoss


3 Answers

The object fstream is not copyable.

If you need to record fstreams in a vector you can declare a std::vector<std::fstream*> and push back the address of the object. Remember that if you save the pointer, then you must ensure that, when you access it, the object is still alive.

like image 87
Luca Martini Avatar answered Oct 08 '22 10:10

Luca Martini


In C++ 2011 the concrete stream objects are movable. Howver, to take advantage of this you either need to pass a temporary or allow the object to be moved:

std::vector<std::ofstream> files;
files.push_back(std::ofstream("f1"));
std::ofstream file("f2");
files.push_back(std::move(file));

Note that you can't use the file variable after this as the stream was moved into files.

like image 40
Dietmar Kühl Avatar answered Oct 08 '22 11:10

Dietmar Kühl


To use a class with a vector, it must be copyable. fstream is not.

See: C++ std::ifstream in constructor problem

Edit: If you need to have multiple references to the same fstream, you can use shared_ptr to manage them. Try something like:

std::vector< std::shared_ptr<fstream> > TEST
like image 40
stanwise Avatar answered Oct 08 '22 11:10

stanwise