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