Loading fstreams in 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 will not compile:

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

Is there any special reason? Is there any way to get fstream dynamic list?

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 ==========
+5
source share
4 answers

The object fstreamcannot be copied.

If you need to write fstreamto vector, you can declare std::vector<std::fstream*>and send the address of the object. Remember that if you save the pointer, you must make sure that when it is accessed, the object is still alive.

+11
source

++ 2011 . , , , :

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

, file, files.

+5

, . fstream .

: ++ std:: ifstream

: , shared_ptr . - :

std::vector< std::shared_ptr<fstream> > TEST
+3

The basic requirement for the type to be inserted into the vector is that the object must be copied, fstreamnot copied, and therefore you get compiler errors.

+1
source

All Articles