STL之vector内存释放

相信搜索这个问题的大家已经知道vector的clear()只能对vector中的元素个数清空,但是并不能释放相应的空间。

swap 释放内存方法

网上有不少相关的文章介绍利用vector的swap()进行内存释放,总体上有两种方法:

以std::vector test(100,10);为例

方法一:std::vector().swap(test);
方法二:std::vector(test).swap(test);(实际上是不完整的)

但是这些博客没有说明两者的区别,使得刚接触这个问题的小伙伴们感到迷惑。
接下来我以一段实际的代码测试来阐述两者的区别:

code1:

#include <vector>
#include <iostream>

using std::cout;
using std::endl;

std::vector<int> test(100,10);
cout<< test.size()<<endl;
cout << test.capacity()<<endl;
std::vector<int>().swap(test);
cout << test.size()<<endl;
cout << test.capacity()<<endl;

输出:

值得注意的是:这里在调用swap()之前,并不需要调用test.clear();

code2:
#include <vector>
#include <iostream>

using std::cout;
using std::endl;

std::vector<int> test(100,10);
cout<< test.size()<<endl;
cout << test.capacity()<<endl;
std::vector<test>().swap(test);
cout << test.size()<<endl;
cout << test.capacity()<<endl;

输出:
这里写图片描述

分析:
这里把std::vector().swap(test)换成了std::vector(test).swap(test).跟上一段代码一样,这里在调用swap()之前没有调用clear().从输出结果来看,不能完成内存的释放。

code3:
#include <vector>
#include <iostream>

using std::cout;
using std::endl;

std::vector<int> test(100,10);
cout<< test.size()<<endl;
cout << test.capacity()<<endl;
test.clear();
std::vector<test>().swap(test);
cout << test.size()<<endl;
cout << test.capacity()<<endl;

输出:
这里写图片描述

分析:从输出来看,很好的完成了内存释放。code3与code2的区别在于code3在调用swap()之前调用了clear().

结论:

所以code1与code3才是实现vector内存释放的正确方法。code1(方法一)的更加简明些,code2(方法二)要求先调用clear().

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值