10

我正在使用 astd::deque来存储相当多的对象。如果我删除一堆这些对象,在我看来,它的内存使用量并没有减少,其方式与 std::vector 类似。

有没有办法减少它?我知道在向量中你必须使用“交换技巧”,我认为它也可以在这里工作,但我宁愿避免这样做,因为它需要复制容器中剩下的所有元素(因此要求你有足够的内存来存储每个对象两次)。我对双端队列的实现并不十分熟悉,但我对它的理解是,在没有大量副本的情况下可能实现这样的事情(而使用向量显然不是)。

我正在使用 VC++ (Dinkumware) STL,如果这有什么不同的话。

4

4 回答 4

15

There is no way to do this directly in a std::deque. However, it's easy to do by using a temporary (which is basically what happens in a std::vector when you shrink it's capacity).

Here is a good article on std::deque, comparing it to std::vector. The very bottom shows a clean way to swap out and shrink a vector, which works the same with deque.

于 2009-08-07T01:29:40.340 回答
5

作为对此的补充信息:

在 C++0x/C++11 中,双端队列(和其他几个容器)有一个名为“shrink_to_fit”的新函数,它将删除多余的项目并基本上对齐容量() == 大小()

于 2011-04-29T17:04:01.280 回答
4

The memory size of a deque might or might not shrink. When and How this happens is implementation specific. Unfortunately you don't have much manual control over this since deques lack even capacity() or reserve().

I'd suggest swap() if you indeed detect memory release isn't being performed at your convenience.

An intimate knowledge of deque memory management may probably be gained from Dikum website (this is your current implementation, right?)

于 2009-08-07T01:32:49.710 回答
1

std::deque 会将内存返回给它的分配器。通常这个分配器不会将内存返回给操作系统。在这种情况下,似乎内存没有“释放”。良好的内存泄漏检测器将在内存返回分配器后立即得到满足,并了解并非所有内存都由free().

于 2009-08-07T10:12:02.940 回答