C++ 删除向量、对象、空闲内存

C++ delete vector, objects, free memory(C++ 删除向量、对象、空闲内存)
本文介绍了C++ 删除向量、对象、空闲内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我对在 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++ 删除向量、对象、空闲内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)