释放内存.避免内存泄漏 [英] Dealocating memory. Avoiding memory leaks

查看:124
本文介绍了释放内存.避免内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class sortedVector
{
	
public:
	int* vect;
	int length;
	int size;

	sortedVector(int n):size(n)
	    { 
              length=0;
              vect=new int[n];         
            }
	~sortedVector()
	    {delete [] vect; }
//methods....
};
void main()
{
sortedVector v(5);
//....
v.~sortedVector(); //if I write this, I get a run-time error ASSERTION_FAIL

}



该程序可以正常运行,这不是问题所在.正如我所说,如果我调用析构函数,则会收到运行时错误,如果不调用它,则一切正常.我的问题是:如果我不显式调用析构函数,则内存是否已销毁?因为我想避免内存泄漏.



The program runs ok, not this is the problem. As I said, if I call the destructor, I get that run-time error, if I don''t call it everything is OK. My question is: IS THE MEMORY DEALOCATED if I don''t call the destructor explicitly? because I want to avoid memory leaks.
Thanks in advance!

推荐答案

您不得将析构函数作为函数调用.析构函数和构造函数是在删除时调用的函数,或者在离开或进入声明范围(堆栈)时被隐式调用的新函数或隐式函数.
在您的情况下,析构函数将被调用两次.
如果您在析构函数中释放已分配的内存-一切正常.
问候.
You must not call the destructor as function. The destructor and constructor are functions they are called on delete or new or implicit on leaving or entering the declaration scope (stack).
In your case your destructor is called twice.
If you free your allocated memory in destructor - everything is ok.
Regards.


这篇关于释放内存.避免内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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