C ++删除矢量,对象,空闲内存 [英] C++ delete vector, objects, free memory

查看:133
本文介绍了C ++删除矢量,对象,空闲内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于在C ++中删除事物我完全感到困惑
如果我声明一个对象数组,如果我使用 clear()函数。我可以确定内存已被释放吗?

I am totally confused with regards to deleting of things in C++ If I declare an array of objects and if I use the clear() 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();

如果这种情况改变为对象的指针,答案是否与上面一样? / p>

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆