c++ - Why can I have a std::vector<std::ofstream*> but not a std::vector<std::ofstream>? -
i have following test code in have parameter fs container of ofstreams:
#include <fstream> #include <vector> #include <cstdlib> #include <cstdio> int main() { // container of ofstream(s) std::vector<std::ofstream> fs; // instantiate ofstream std::ofstream of("myfile.txt"); // push container fs.push_back(of); return 0; } this not compile @ all. whereas when change container of ofstream container of pointers ofstreams, code compiles:
#include <fstream> #include <vector> #include <cstdlib> #include <cstdio> int main() { // container of ofstream(s) std::vector<std::ofstream*> fs; // instantiate ofstream std::ofstream * of = new std::ofstream("myfile.txt"); // push container fs.push_back(of); return 0; } why this?
when call push_back(of) on vector, tries add copy of object of vector. (c++ loves making copies of things). in case, you're trying copy ofstream, isn't permitted. intuitively, it's not clear mean have copy of ofstream, spec prohibits it.
on other hand, suppose have vector of ofstream*s. now, if try push_back pointer ofstream, c++ interprets mean should put copy of pointer vector, , that's okay because pointers can copied around.
there's third option, though, if have recent compiler. c++ introduced idea of move semantics, instead of trying copy file stream vector, can move file stream vector. therefore write this:
int main() { // container of ofstream(s) std::vector<std::ofstream> fs; // instantiate ofstream std::ofstream of("myfile.txt"); // push container fs.push_back(std::move(of)); return 0; } after doing this, variable of won't refer original file stream anymore; it'll instead have dummy value. however, vector contain stream used stored in of.
Comments
Post a Comment