std::deque<T,Allocator>::shrink_to_fit
来自 cppreference.cn
void shrink_to_fit(); |
||
请求移除未使用的容量。
这是一个非强制性请求,旨在减少内存使用,而不更改序列的大小。 是否满足请求取决于实现。
所有迭代器(包括 end()
迭代器)和对元素的所有引用都将失效。
如果 |
(自 C++11 起) |
目录 |
[编辑] 复杂度
最多与容器的大小呈线性关系。
异常如果抛出异常,但不是由非 CopyInsertable |
(自 C++11 起) |
[编辑] 注意
在 libstdc++ 中,C++98 模式下 不提供 shrink_to_fit()
。
[编辑] 示例
运行此代码
#include <cstddef> #include <deque> #include <iostream> #include <new> // Minimal C++11 allocator with debug output. template<class Tp> struct NAlloc { typedef Tp value_type; NAlloc() = default; template<class T> NAlloc(const NAlloc<T>&) {} Tp* allocate(std::size_t n) { n *= sizeof(Tp); std::cout << "allocating " << n << " bytes\n"; return static_cast<Tp*>(::operator new(n)); } void deallocate(Tp* p, std::size_t n) { std::cout << "deallocating " << n*sizeof*p << " bytes\n"; ::operator delete(p); } }; template<class T, class U> bool operator==(const NAlloc<T>&, const NAlloc<U>&) { return true; } template<class T, class U> bool operator!=(const NAlloc<T>&, const NAlloc<U>&) { return false; } int main() { // std::queue has no capacity() function (like std::vector). // Because of this, we use a custom allocator to show the // working of shrink_to_fit. std::cout << "Default-construct deque:\n"; std::deque<int, NAlloc<int>> deq; std::cout << "\nAdd 300 elements:\n"; for (int i = 1000; i < 1300; ++i) deq.push_back(i); std::cout << "\nPop 100 elements:\n"; for (int i = 0; i < 100; ++i) deq.pop_front(); std::cout << "\nRun shrink_to_fit:\n"; deq.shrink_to_fit(); std::cout << "\nDestroy deque as it goes out of scope:\n"; }
可能的输出
Default-construct deque: allocating 64 bytes allocating 512 bytes Add 300 elements: allocating 512 bytes allocating 512 bytes Pop 100 elements: Run shrink_to_fit: allocating 64 bytes allocating 512 bytes allocating 512 bytes deallocating 512 bytes deallocating 512 bytes deallocating 512 bytes deallocating 64 bytes Destroy deque as it goes out of scope: deallocating 512 bytes deallocating 512 bytes deallocating 64 bytes
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 850 | C++98 | std::deque 缺少显式的 shrink-to-fit 操作 |
已提供 |
LWG 2033 | C++98 C++11 |
1. 缺少复杂度要求 (C++98) 2. 未要求 T 为 MoveInsertable (C++11) |
1. 已添加 2. 已要求 |
LWG 2223 | C++98 C++11 |
1. 引用、指针和迭代器未失效 (C++98) 2. 没有异常安全保证 (C++11) |
1. 它们可能会失效 2. 已添加 |
[编辑] 参见
返回元素数量 (公共成员函数) |