delete删除的该指针指向的内存,指针变成一个野指针
delete指针后,指针不一定为NULL:
//BanaryNode是一个自定义的类
BanaryNode* tree = new BanaryNode();
delete tree;
if(tree != NULL)
std::cout<<"NOT NULL"<<std::endl;
//最后输出为NOT NULL
- 为了保证delete后指针安全,所以需要将指针赋为NULL
BanaryNode* tree = new BanaryNode();
delete tree;
tree = NULL;
- 在函数传递指针过程中,会出现这样的问题:
void BanaryRemove(BanaryNode* tree)
{
if(tree == NULL)
return;
delete tree;
tree = NULL;
}
BanaryNode* tree = new BanaryNode();
BanaryRemove(tree);
if(tree != NULL)
std::cout<<"NOT NULL"<<std::endl;
//最后输出为NOT NULL
因为 BanaryRemove(BanaryNode* tree)中传递的值tree的值,在函数中将 tree = NULL,只是将tree的副本赋值为NULL。
可通过引用传递解决问题,通过直接对tree的操作而不是tree的副本
void BanaryRemove(BanaryNode* &tree)
{
if(tree == NULL)
return;
delete tree;
tree = NULL;
}