C++ delete vector, objects, free memory(C++ 删除向量、对象、空闲内存)
问题描述
我对在 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++ 删除向量、对象、空闲内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 删除向量、对象、空闲内存
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
