6

Why does the following not work:

#include <iostream>
#include <fstream>
#include <stack>

std::stack<std::ifstream> s;

-PT

4

3 回答 3

10

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 an operator=. std::ifstream has 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 of std::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.

于 2010-03-02T13:44:32.490 回答
2

因为流是不可复制的,您可以在技术上将它们放入标准容器中。

但是我们可以通过存储指向流的指针来解决这个问题。但是您不想将指向流的指针(特别是如果它们是动态分配的)存储在标准容器中。因此,我们寻求解决方案。

Boost 有指针容器的概念。
这允许您动态分配对象并将指针存储在指针容器中,然后指针容器获得对象的所有权并让您可以访问动态对象,就像它是对象(而不是指针)一样。

因为指针容器拥有所有权,所以您不必担心删除对象。容器会这样做。

因为它允许以对象而不是指针的形式访问包含的对象,所以它允许您以更自然的方式在标准算法中使用流(与指针容器一起使用)。

于 2010-03-02T14:04:01.063 回答
0

在这里支持泰勒(在投票 +1 之后)。

stl 容器在您提供给它们的对象的所有位置上进行复制。如果你愿意,你可以通过给他们特殊的对象来处理这个问题,这些对象带有精心设计的复制构造函数和带有引用计数等的解构函数。

一般来说,我觉得那样太麻烦了。根据经验,仅使用容器中的小物件。如果要创建一堆结构或类,请改用指向它们的指针。

于 2010-03-02T14:00:37.433 回答