C++使用new 一个指针后,用delete删除,如果是new [],那么用delete []删除,是的,大家都知道,但不要忘了,删除指针之后,还要给指针赋值NULL,避免误用了野指针。
int main(int argc, char* argv[])
{
int *ip1;
int i100 = 100;
ip1 = new int;
*ip1 = 100;
cout << "*ip1 is: " << *ip1 << endl;
cout << "ip1 is: " <<ip1 << endl;
delete ip1;
cout << "delete ip1" << endl;
cout << "*ip1 is: " << *ip1 << endl;
cout << "ip1 is: " <<ip1 << endl;
ip1 = NULL;
cout << "ip1 = NULL: " << endl;
//cout << "*ip1 is: " << *ip1 << endl; //ip1 = NULL,*ip已经不存在,不能再使用。
cout << "ip1 is: " <<ip1 << endl;
return 0;
}
如果重复删除一个非空指针,那是绝对危险的,系统会直接崩溃。
int main(int argc, char* argv[])
{
int *ip1;
int i100 = 100;
ip1 = new int;
*ip1 = 100;
cout << "*ip1 is: " << *ip1 << endl;
cout << "ip1 is: " <<ip1 << endl;
delete ip1;
cout << "delete ip1" << endl;
cout << "*ip1 is: " << *ip1 << endl;
cout << "ip1 is: " <<ip1 << endl;
delete ip1; //重复删除一个非空指针,系统会直接崩溃的。
// ip1 = NULL;
// cout << "ip1 = NULL: " << endl;
// cout << "*ip1 is: " << *ip1 << endl; //ip1 = NULL,*ip已经不存在,不能再使用。
// cout << "ip1 is: " <<ip1 << endl;
return 0;
}
所以,要养成习惯,delete指针后马上将指针赋值为NULL,NULL指针是允许重复delete的。
int main(int argc, char* argv[])
{
int *ip1;
int i100 = 100;
ip1 = new int;
*ip1 = 100;
cout << "*ip1 is: " << *ip1 << endl;
cout << "ip1 is: " <<ip1 << endl;
delete ip1;
cout << "delete ip1" << endl;
cout << "*ip1 is: " << *ip1 << endl;
cout << "ip1 is: " <<ip1 << endl;
ip1 = NULL;
cout << "ip1 = NULL: " << endl;
delete ip1; //NULL运行重复delete
delete ip1;
delete ip1;
// cout << "*ip1 is: " << *ip1 << endl; //ip1 = NULL,*ip已经不存在,不能再使用。
cout << "ip1 is: " <<ip1 << endl;
return 0;
}
所以,标准的安全的用法是delete指针前先进行非空判断。
int main(int argc, char* argv[])
{
int *ip1;
int i100 = 100;
ip1 = new int;
*ip1 = 100;
cout << "*ip1 is: " << *ip1 << endl;
cout << "ip1 is: " <<ip1 << endl;
if(NULL != ip1)
{
delete ip1;
cout << "delete ip1" << endl;
cout << "*ip1 is: " << *ip1 << endl;
cout << "ip1 is: " <<ip1 << endl;
ip1 = NULL;
cout << "ip1 = NULL: " << endl;
// cout << "*ip1 is: " << *ip1 << endl; //ip1 = NULL,*ip已经不存在,不能再使用。
cout << "ip1 is: " <<ip1 << endl;
}
return 0;
}
如果delete了一个指针,但是没有将它赋值为NULL,此时还误用解引用该指针(*ip1)时,系统不会崩溃,解出来的值是系统随机分配值;
但是如果delete了一个指针,且已将它赋值为NULL,此时还误用解引用该指针(*ip1)时,系统会崩溃,cout << "*ip1 is: " << *ip1 << endl; 。
最后,提醒下,如果指针指向了一个对象,而你想删除该指针,那是容易犯的低级错误,系统是会毫不留情的崩溃。
int main(int argc, char* argv[])
{
int *ip1;
int i100 = 100;
ip1 = new int;
ip1 = &i100;
if(NULL != ip1)
{
delete ip1; //ip1指向i100的地址,删除ip1就是要删除i100,是禁止的,系统也会直接崩溃。
cout << "delete ip1" << endl;
cout << "*ip1 is: " << *ip1 << endl;
cout << "ip1 is: " <<ip1 << endl;
ip1 = NULL;
cout << "ip1 = NULL: " << endl;
// cout << "*ip1 is: " << *ip1 << endl; //ip1 = NULL,*ip已经不存在,不能再使用。
cout << "ip1 is: " <<ip1 << endl;
}
return true;
}