自身内部的类和内存泄漏 [英] Class inside itself and memory leaks

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

问题描述

聪明的人,
我有一个关于自身内部课程的问题.这是一个伪代码:

Hi smart ones,
I have a question regarding a class inside itself. Here is a dummy code:

//.h
class MyClass{
public:
 MyClass();
 virtual ~MyClass();
 
 MyClass* prev;
 void Set_Prev(MyClass& cap);
};

//.cpp
void MyClass::Set_Prev(MyClass& cap){
   prev = new MyClass();
   *prev = cap;
}



现在,这里一切都很好,但是我遗漏了内存.如何克服这一点,因为我无法立即调用delete,因此prev用于代码的其他部分.在MyClass的解构函数中调用delete会给我运行时错误.任何输入将不胜感激:)

OP的非解决方案中的[edit]添加已移至此处[/edit]
如何确保它是深层副本?我用新的first初始化,否则会在operator =中添加错误.



Now everything is OK here, but I''m left with a memory leak. How to overcome this, as I can''t call delete right away, the prev is used in other parts in the code. And calling delete in MyClass''s deconstructor is giving me errors on runtime. Any input will be appreciated :)

[edit] addition by the OP in a non-solution moved here[/edit]
How to be sure that it is a deep copy? I initialise with new first, as otherwise I get error in the operator= I have added to the class.

推荐答案

请参阅下面的代码内部注释


See comments inside code below


//.h
class MyClass{
public:
 MyClass();
 virtual ~MyClass();
 
 MyClass* prev;
 void Set_Prev(MyClass& cap);
};
 
//.cpp
void MyClass::Set_Prev(MyClass& cap){
   prev = new MyClass();    
//Why are you doiing this. here you are allocating memory for it and then not using it at all  and in next line you have attached the pointer to something else coming from outside. so there are as many objects leaked as many times you call this fucntion. remove this line.
   *prev = cap;
}



[edit]对不起,我想我上次误解了正确的做法,这是



[edit] sorry, i think i misinterpreted last time the right way to do this would be

//.cpp
void MyClass::Set_Prev(MyClass& cap){
if(prev != 0)
{
   delete prev;
   prev = 0;
}
   prev = new MyClass();

   *prev = cap;   //just make sure you have proper copy constructor doing deep copy not shallow one.
}


如果您只是要用cap覆盖它,为什么要新建prev?

删除prev = new MyClass();.

希望这会有所帮助,
Fredrik
Why do you new up prev if you''re just going to overwrite it with cap?

Remove the prev = new MyClass();.

Hope this helps,
Fredrik


如果引用很好,请尝试:

If a reference is fine, try:

void MyClass::Set_Prev(MyClass& cap){
   prev = ∩
}



这会将prev指针设置为指向cap.



That sets the prev pointer to point to cap.


这篇关于自身内部的类和内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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