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 withdecoy
.先创造一个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 数据