删除空指针 [英] Deleting a null pointer

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

问题描述

可能重复:
是否有任何理由检查

删除之前是否为空指针?

我经常在代码中看到以下内容:

if(pointer)
    delete pointer;

据我了解,删除空指针是安全的,那么此检查的目的是什么?

解决方案

delete将为您检查指针是否为NULL,所以您说对了,不需要检查.

您可能还会看到有人将指针删除后将指针设置为NULL ,这样您就不会做任何愚蠢的尝试,例如尝试使用不再属于您的内存或阻止您删除指针.指针两次,将导致错误.

Possible Duplicate:
Is there any reason to check for a NULL pointer before deleting?

I often see the following in code:

if(pointer)
    delete pointer;

To my understanding it is safe to delete a null pointer, so what is the point of this check?

解决方案

delete will check if the pointer is NULL for you, so you're right that the check isn't needed.

You might also see that some people set the pointer to NULL after it's deleted so that you don't do anything stupid like try and use memory that is no longer yours or stop you from deleting the pointer twice, which will cause an error.

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

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