删除指针并将其设置为nullptr有什么区别? [英] What's the difference between delete-ing a pointer and setting it to nullptr?

查看:306
本文介绍了删除指针并将其设置为nullptr有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是说delete pointerpointer = nullptr一样吗?可能不是,但是后者会释放内存吗? delete pointer; pointer = nullptr/pointer = nullptr; delete pointer呢?为什么不使用它来提供一种安全的方法来在需要时过早地删除指针,而该指针通常会在其他时间被删除并导致正常删除的错误呢?

解决方案

这是不一样的,因为尽管您可能将指针设置为null,但指针指向的内容仍会占用空间. >

delete pointer;
pointer = NULL;

很好,但是

pointer = NULL;
delete pointer;

不是,因为您已经将指针设置为NULL,所以delete命令将没有要删除的内容(或认为如此).您现在遇到了内存泄漏,因为指针之前指向的任何内容(例如链表)现在都漂浮在内存中的某个位置,并且程序无法跟踪.

Is saying delete pointer and pointer = nullptr the same? Probably not, but does the latter free up memory? What about delete pointer; pointer = nullptr / pointer = nullptr; delete pointer? Why not use that to make a safe way to delete pointers prematurely if required, where they would normally be deleted some other time and cause an error with a normal delete?

解决方案

It is not the same, because while you may be setting the pointer to null, the contents that the pointer pointed to would still be taking up space.

Doing

delete pointer;
pointer = NULL;

Is fine, but

pointer = NULL;
delete pointer;

Is not, since you already set the pointer to NULL, the delete command will have nothing to delete (or so it thinks). You now have a memory leak because whatever the pointer pointed to beforehand (let's say a linked list) is now floating somewhere in your memory and is untrackable by the program.

这篇关于删除指针并将其设置为nullptr有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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