Why can't I create std :: stack from std :: ifstreams?

Why the following does not work:

#include <iostream> #include <fstream> #include <stack> std::stack<std::ifstream> s; 

-pt

+6
c ++ stack iostream stl ifstream
source share
3 answers

std::stack (like all STL containers) requires that its contained type be "assignable". In STL-talk, this means that it must have a copy constructor and operator= . std::ifstream does not have any of them.

You can imagine why you do not want 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 reading or copying one copy affect the position of another copy? Should closing one thread close another? and etc.

If you want to have a β€œ std::ifstream s” container, then what you really have to do is β€œa std::ifstream* s container”. Non-constant pointers are always assigned. The caveat is that in this case, of course, you must make sure that you delete the pointers yourself before you destroy the container, since the container will not do this for you.

+10
source share

Since streams are not copied, you can tecxhnicaly put them in standard containers.

But we can get around this by storing the flow pointers. But you do not want to store stream pointers (especially if they are dynamically allocated) in a standard container. Therefore, we strive to enhance the solution.

Boost has the concept of pointer containers.
This allows you to dynamically allocate the object and store the pointer in a container of the pointer, which then becomes the property of the object and gives you access to the dynamic object as if it were an object (not a pointer).

Since the container pointer takes responsibility, you do not have to worry about deleting the object. The container will do this.

Since it provides access to contained objects as objects, rather than pointers, it allows using the stream in standard algorithms in a more natural fashon (in a camp with a container of pointers).

+2
source share

Tyler backup here (after +1 vote).

The stl containers copy all the objects you give them. If you want, you can handle this by providing them with special objects with carefully crafted copy constructors and link count destructors and something else.

As a rule, I find that there are too many problems. As a rule, use only small objects in containers. If you want to create a stack of structures or classes, use pointers instead.

0
source share

All Articles