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 ==========
The object fstream
is not copyable.
If you need to record fstream
s 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.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With