【Example】C++ Vector 的内存强制回收

为什么要对 Vector 进行内存强制回收?

1,Vector 的 clear() 函数仅仅是将 vector 的 size 设置为0,所存储的对象占用的内存并没有被回收。

2,Vector 本身是一个内存只会增长不会减小的容器。

3,最根本目的是减低内存占用、优化内存使用率避免浪费。

 

什么样的 Vector 应当进行手动内存回收?

1,存储大量数据、对内存占用较高的vec。

2,生命周期一直活跃于整个程序生命周期且会被反复clear、再写入的vec。

 

用什么方法回收?

clear 后直接空 swap 一次。

如果存储的是裸指针,必须先遍历释放裸指针!

 

#include <iostream>

#include <vector>
using std::vector;

// 随便创建一个结构体
typedef struct Point {
    int x;
    int y;
    int val;

    // 顺带演示统一初始化 (现代C++)
    Point(int x, int y, int value) : x(x), y(y), val(value) {};
};

int main()
{
    // 定义一个 vector
    vector<Point> points;

    // 随便填充一下
    for (size_t i = 0; i < 9000; i++)
    {
        points.push_back(Point(i, i, -99999));
    }

    // clear清理vector
    points.clear();

    // 输出一下 vector 长度和容量
    std::cout << "Vector Size: " << points.size() << std::endl;          // size: 0
    std::cout << "Vector Capacity: " << points.capacity() << std::endl;  // capacity: 12138


    std::cout << "===========================" << std::endl;

    // 从这里将 vector 的容量强制置空
    vector<Point>().swap(points);

    // 再次输出一下
    std::cout << "Vector Size: " << points.size() << std::endl;         // siez: 0
    std::cout << "Vector Capacity: " << points.capacity() << std::endl; // capacity: 0
    
    return EXIT_SUCCESS;
}

 

 

posted @ 2021-12-12 01:10  芯片烤电池  阅读(146)  评论(0编辑  收藏  举报