Why does the following not work:
#include <iostream>
#include <fstream>
#include <stack>
std::stack<std::ifstream> s;
-PT
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
std::stack(like all STL containers) requires that its contained type be “assignable”. In STL-speak, that means that it must have a copy constructor and anoperator=.std::ifstreamhas neither of these.You can imagine why you would not want to be able to copy and assign I/O streams; the semantics of what should happen when there are two copies of the same stream are not obvious. Should a read from or write to one copy affect the position of the other copy? Should closing one stream close the other? etc.
If you want to have “a container of
std::ifstreams”, then what you really should make is “a container ofstd::ifstream*s”. Non-const pointers are always assignable. The caveat is that in this case of course you have to make sure that you delete the pointers yourself before destructing the container, since the container will not do that for you.