删除VS空VS免费C ++ [英] delete vs NULL vs free in c++

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

问题描述

是删除一个指针,它设置为空,并且释放它的区别。

 删除PTR;

VS。

  PTR = NULL;

VS

 免费(PTR);


解决方案

您的问题建议您来自有垃圾收集的语言。 C ++没有垃圾收集。

如果设置一个指针为NULL,这不会导致存储器返回到可用内存池中。如果没有其它指针指向的内存块,你现在只是有剩下的分配,但现在无法访问内存中的孤立块 - 一个泄漏。仅泄漏导致程序,如果他们建立的地方没有记忆留给分配点崩溃。

还有相反的情况,在那里你使用指针删除 A的内存块,后来尝试访问内存虽然它仍然分配。这可能是因为调用删除上的指针不会设置指针为NULL - 它仍然指向的内存,previously被分配的地址。一个指向内存不再分配被称为悬摆指针并访问它通常会导致奇怪的程序行为和崩溃,因为它的内容很可能不是你所期待的 - 那一块内存可有自从被重新分配用于其他目的。

作为stinky472提到,的另一个区别删除免费()是只有前者调用对象的析构函数。 (请记住,你必须调用删除与分配的对象上免费() 分配的内存的malloc() - 他们不能混)在C ++中,它总是最好的,如果可以使用静态分配,但如果没有,那么preFER 的malloc()

what is the difference between deleting a pointer, setting it to null, and freeing it.

delete ptr;

vs.

ptr=NULL;

vs.

free(ptr);

解决方案

Your question suggests that you come from a language that has garbage collection. C++ does not have garbage collection.

If you set a pointer to NULL, this does not cause the memory to return to the pool of available memory. If no other pointers point to this block of memory, you now simply have an "orphaned" block of memory that remains allocated but is now unreachable -- a leak. Leaks only cause a program to crash if they build up to a point where no memory is left to allocate.

There's also the converse situation, where you delete a block of memory using a pointer, and later try to access that memory as though it was still allocated. This is possible because calling delete on a pointer does not set the pointer to NULL -- it still points to the address of memory that previously was allocated. A pointer to memory that is no longer allocated is called a dangling pointer and accessing it will usually cause strange program behaviour and crashes, since its contents are probably not what you expect -- that piece of memory may have since been reallocated for some other purpose.

[EDIT] As stinky472 mentions, another difference between delete and free() is that only the former calls the object's destructor. (Remember that you must call delete on an object allocated with new, and free() for memory allocated with malloc() -- they can't be mixed.) In C++, it's always best to use static allocation if possible, but if not, then prefer new to malloc().

这篇关于删除VS空VS免费C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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