问题描述
我对在 C++ 中删除内容完全感到困惑.如果我声明了一个对象数组并且我使用了 clear()
成员函数.我能确定内存被释放了吗?
I am totally confused with regards to deleting things in C++. If I declare an array of objects and if I use the clear()
member function. Can I be sure that the memory was released?
例如:
tempObject obj1;
tempObject obj2;
vector<tempObject> tempVector;
tempVector.pushback(obj1);
tempVector.pushback(obj2);
我可以安全地调用 clear 来释放所有内存吗?还是需要遍历一遍才能删除?
Can I safely call clear to free up all the memory? Or do I need to iterate through to delete one by one?
tempVector.clear();
如果把这个场景换成一个对象的指针,答案会不会和上面一样?
If this scenario is changed to a pointer of objects, will the answer be the same as above?
vector<tempObject> *tempVector;
//push objects....
tempVector->clear();
推荐答案
你可以调用clear,这会销毁所有的对象,但不会释放内存.循环遍历各个元素也无济于事(您甚至建议对对象采取什么行动?)您可以这样做:
You can call clear, and that will destroy all the objects, but that will not free the memory. Looping through the individual elements will not help either (what action would you even propose to take on the objects?) What you can do is this:
vector<tempObject>().swap(tempVector);
这将创建一个没有分配内存的空向量,并将其与 tempVector 交换,从而有效地释放内存.
That will create an empty vector with no memory allocated and swap it with tempVector, effectively deallocating the memory.
C++11 也有函数 shrink_to_fit
,你可以在调用 clear() 之后调用它,理论上它会缩小容量以适应大小(现在是 0).然而,这是一个非绑定请求,您的实现可以随意忽略它.
C++11 also has the function shrink_to_fit
, which you could call after the call to clear(), and it would theoretically shrink the capacity to fit the size (which is now 0). This is however, a non-binding request, and your implementation is free to ignore it.
这篇关于C++ 删除向量、对象、空闲内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!