【代码】Opencv 和C++ 中的内存管理

本文介绍了C++ STL容器中vector的三种释放内存的方法:使用clear和shrink_to_fit组合、swap与临时对象交换,以及结合clear与swap操作。这些方法有助于优化内存使用并提高程序效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. STL容器中 【vector】 的释放方式

 

看到有两种方式, 比如说创建了    vector<Rect>    rect;

(1)

rect.clear();
rect.shrink_to_fit();

(2)

vector<Rect>().swap(rect);

(3)

rect.clear();
vector<Rect>(rect).swap(rect);

根据 https://stackoverflow.com/questions/3477715/c-vectorclear的说法,

It creates a new vector of Weight objects (which will be empty) and swaps it with decoy.

先创造一个weight的对象,然后和decoy交换。

The reason for this is that by default, std::vector<t>::clear often doesn't actually reduce the storage used by a vector, it merely destroys all the objects contained there. This way, the vector has room to store more objects without reallocation in the future.

原因是:clear通常不会减少vector的内存,他只是毁掉了vector容器里存放的内容,因此,即使不重新分配内存,容器还是可以有空间储存物体。

Sometimes, however, you want to trim the capacity in the vector. Swapping with a newly created vector (which lives until the end of it's line, and is therefore destroyed there) frees all the memory allocated by the vector.

然而有时候,我们希望整理vector占用的内存空间,所以我们用一个新的空的容器来代替它,直到运行结束。

也就是说,clear是把容器里的东西全扔掉,但是容器还在那里,swap相当于把这个容器打碎。所以第一种方法里,使用了shrink_to_fit函数,这句话的作用是,清理容器的空间,让容器的大小根据它实际的存储的内容来确定。形象的说,就是把放在大箱子里的东西,用一个刚好可以放下他们的小的容器来装,避免空间浪费。

 

2. cvCloneImage复制Iplimage 数据

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值