std::deque<T,Allocator>:: shrink_to_fit
|
void
shrink_to_fit
(
)
;
|
(自 C++26 起为 constexpr) | |
请求移除未使用的容量。
这是一个非强制性请求,旨在不改变序列大小的情况下减少内存使用。该请求是否被满足取决于具体实现。
所有迭代器(包括
end()
迭代器)及所有对元素的引用都会失效。
|
如果
|
(since C++11) |
目录 |
复杂度
最多与容器大小成线性关系。
异常
若抛出的异常并非来自非
CopyInsertable
类型
|
(C++11 起) |
注释
在 libstdc++ 中,
shrink_to_fit()
在 C++98 模式下
不可用
。
示例
#include <cstddef> #include <deque> #include <iostream> #include <new> // 带调试输出的最小C++11分配器 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没有capacity()函数(与std::vector不同) // 因此我们使用自定义分配器来展示shrink_to_fit的工作原理 std::cout << "默认构造deque:\n"; std::deque<int, NAlloc<int>> deq; std::cout << "\n添加300个元素:\n"; for (int i = 1000; i < 1300; ++i) deq.push_back(i); std::cout << "\n弹出100个元素:\n"; for (int i = 0; i < 100; ++i) deq.pop_front(); std::cout << "\n运行shrink_to_fit:\n"; deq.shrink_to_fit(); std::cout << "\n当deque超出作用域时销毁:\n"; }
可能的输出:
默认构造deque: allocating 64 bytes allocating 512 bytes 添加300个元素: allocating 512 bytes allocating 512 bytes 弹出100个元素: 运行shrink_to_fit: allocating 64 bytes allocating 512 bytes allocating 512 bytes deallocating 512 bytes deallocating 512 bytes deallocating 512 bytes deallocating 64 bytes 当deque超出作用域时销毁: deallocating 512 bytes deallocating 512 bytes deallocating 64 bytes
缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
| 缺陷报告 | 适用标准 | 发布时行为 | 正确行为 |
|---|---|---|---|
| LWG 850 | C++98 |
std::deque
缺少显式缩容操作
|
已提供 |
| 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. 已添加 |
另请参阅
|
返回元素数量
(公开成员函数) |