为什么在 C++ 中使用删除后指针不为 NULL [英] Why pointer is not NULL after using delete in C++

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

问题描述

我写了这个,想知道为什么已删除"没有显示为输出.

I wrote this and wondering why "deleted" isn't showing as output.

int *p=NULL;
p=new int(10);
cout<<*p<<endl;
delete p;
if(p==NULL)cout<<"deleted"<<endl;

有人可以解释为什么在使用 delete 后不打印以及为什么 delete 不会使指针为 NULL 吗?

Can Someone explain why it isn't printing after using delete and why delete isn't making the pointer NULL ?

推荐答案

这是因为当您说 delete p 时,您正在删除一个指向内存的指针,这会完全擦除对您分配的新内存的引用.当您说 if p==NULL 时,您正在检查指针是否设置为 null,而实际上它指向的内存已取消分配,因此指针未指向任何内容.这与在 C++ 中指向 NULL 的含义不同.

It's because when you say delete p you're deleting a pointer to memory which completely erases the reference to the new memory you allocated. When you say if p==NULL you're checking to see if the pointer was set to null when in fact the memory that it was pointing to was de-allocated so the pointer isn't pointing to anything. Which doesn't mean the same as having it point to NULL in C++.

这篇关于为什么在 C++ 中使用删除后指针不为 NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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