C ++中的NULL和指针 [英] NULL and pointers in C++

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

问题描述





如果我这样做



Hi,

if I do

int * x = new int;
delete x;
if(x)
// do something abc





以上代码评估的内容是什么?

我认为它将评估为真(例如,做某事abc)?!



这很奇怪,因为我如何检查指针是否被删除?





和ps。什么是NULL以及为什么需要它?



What will the above code evaluate to?
I think it will evaluate to true (e.g., "do something abc")?!

This is strange because how then I check if a pointer was deleted or not?


and ps. what is NULL and why is it needed?

推荐答案

它将评估为true,因为删除分配给指针的内存不会改变指针中的值:it仍在解决旧的,释放的记忆。由于所有有效指针都非零(除了一个非常特殊的情况:NULL) x 将评估为非零,这是真的。



这是NULL的一种用法 - 用于检测指针何时无效 而不试图使用 ,这会导致异常,如果指针确实无效。



所以当你使用 delete 时,也要将指针设置为NULL:

It will evaluate to true, because deleting the memory allocated to a pointer does not change the value in the pointer: it remains addressing the old, freed memory. Since all valid pointers are non-zero (except one very special case: NULL) x will evaluate to non-zero, which is true.

This is one of the uses of NULL - to detect when a pointer is invalid without trying to use it which would cause an exception if the pointer is indeed invalid.

So when you use delete, set the pointer to NULL as well:
int * x = new int;
delete x;
x = NULL;
if(x)
   // Don't do something


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

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