【C++】vector扩容缩容

vector扩容缩容

1 扩容

一般来说,主要是重新分配内存

2 缩容

resize 缩小后,vector 的容量(capacity())可能保持不变,需要显式调用 shrink_to_fit() 来释放内存。

验证代码:

cpp 复制代码
#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() {
    // 使用自定义分配器的 vector
    std::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时,会重新分配空间

检测是否有内存泄漏:

shell 复制代码
valgrind --tool=memcheck --leak-check=full ./your_program
相关推荐
倒头就睡的小比特1 天前
算法竞赛C++常用的STL
c++·算法
weilx12341 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
Smileyqp沛沛1 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光1 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·1 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁1 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven1 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法