将指针设置为空-内存泄漏? [英] Set Pointer To Null - Memory Leak?

查看:122
本文介绍了将指针设置为空-内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



Hi,

vector<unsigned int>* pvecnDigit = new vector<unsigned int>;

pvecnDigit->push_back(2);

pvecnDigit = NULL;



在这里,我没有使用delete杀死向量指针,而是将其设置为NULL.



Here, I did not use delete to kill vector pointer but set it to NULL. Is there any Memory Leak?

推荐答案

是的.由new创建的对象仍然存在,但无法访问.
Yes. The object created by new still exist, but can''t be accessed.


是的,您需要删除pvecnDigit指向的向量:
Yes, you need to delete the vector pointed to by pvecnDigit:
vector<unsigned int="">* pvecnDigit = new vector<unsigned int="">;
pvecnDigit->push_back(2);
delete pvecnDigit;
pvecnDigit = NULL;



最好的问候
Espen Harlinn



Best regards
Espen Harlinn


我想知道您为什么不愿意问,如果您已经知道使用delete.如果您要问的原因是您想知道如何避免必须进行内存分配和释放,则只需将该向量放在堆栈上,而不是在堆上创建它即可:
I wonder why you even bothered to ask, if you already knew about using delete. If your reason for asking is that you want to know how to avoid having to take care of memory allocation and deallocation, just put that vector on the stack, rather than creating it on the heap:
{
  vector<unsigned int> vecnDigit;
  vecnDigit.push_back(2);
}


注意,不是在堆上创建向量,而是将向量的声明和使用放入代码块中,以限制其范围.这样,您对向量的使用仍然仅限于声明和该块末尾之间的代码行.但是,由于它是在堆栈中声明的,因此您无需照顾分配或释放.


Note that instead of creating the vector on the heap, I just put the declaration and use of the vector into a code block, limiting it''s scope. That way your use of that vector is still limited to the lines of code between your declaration, and the end of this block. But as it''s declared on the stack, you don''t need to take care of allocation or deallocation.


这篇关于将指针设置为空-内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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