vector扩容缩容
1 扩容
一般来说,主要是重新分配内存
2 缩容
resize 缩小后,vector 的容量(capacity())可能保持不变,需要显式调用 shrink_to_fit() 来释放内存。
验证代码:
#include <vector>
#include <iostream>template <typename T>
class TrackingAllocator {
public:using value_type = T;TrackingAllocator() = default;// 允许从其他类型的 TrackingAllocator 构造template <typename U>TrackingAllocator(const TrackingAllocator<U>&) {}// 分配内存T* allocate(size_t n) {std::cout << "分配 " << n * sizeof(T) << " 字节" << std::endl;return static_cast<T*>(::operator new(n * sizeof(T)));}// 释放内存void deallocate(T* p, size_t n) {std::cout << "释放 " << n * sizeof(T) << " 字节" << std::endl;::operator delete(p);}// 定义相等比较运算符bool operator==(const TrackingAllocator&) const noexcept {return true; // 无状态分配器,所有实例等价}// 定义不等比较运算符(可选,C++20 前需要)bool operator!=(const TrackingAllocator& other) const noexcept {return !(*this == other);}
};int main() {// 使用自定义分配器的 vectorstd::vector<int, TrackingAllocator<int>> vec;// 测试 resize 缩小是否释放内存vec.resize(1000); // 触发分配std::cout << "Size: " << vec.size() << ", Capacity: " << vec.capacity() << std::endl;vec.resize(10); // 缩小 size,但 capacity 不变std::cout << "Size: " << vec.size() << ", Capacity: " << vec.capacity() << std::endl;vec.shrink_to_fit(); // 显式释放多余内存std::cout << "Size: " << vec.size() << ", Capacity: " << vec.capacity() << std::endl;return 0;
}
测试不同标准库实现的行为:
编译器/库 | resize 缩小是否自动释放内存 |
---|---|
GCC (libstdc++) | 否,需 shrink_to_fit |
Clang (libc++) | 否,需 shrink_to_fit |
MSVC (MSVC STL) | 否,需 shrink_to_fit |
注意:gcc使用shrink_to_fit时,会重新分配空间
检测是否有内存泄漏:
valgrind --tool=memcheck --leak-check=full ./your_program