转载:原地址:http://www.cppblog.com/mzty/archive/2006/07/07/9531.html
方便学习之用
#include "stdafx.h"
#include <iostream>
using namespace std;
void FreePtr1(int* ptr1)
{
delete ptr1;
ptr1 = NULL;
}

void FreePtr2(int*& ptr2)
{
delete ptr2;
ptr2 = NULL;
}
void FreePtr3(int **ptr3)
{
delete *ptr3;
*ptr3 = NULL;
}

void main()
{
cout<<"---------------------------------------"<<endl;
int *p1 = new int;
*p1 = 1;
cout<<"*p1="<<*p1<<endl;
FreePtr1(p1);
cout<<"after call freePtr1"<<endl;
if(p1 != NULL)
{
cout<<"p1 is not null"<<endl;
cout<<"*p1="<<(*p1)<<endl;
}
cout<<"---------------------------------------"<<endl;
int *p2 = new int;
*p2 = 2;
cout<<"*p2="<<*p2<<endl;
FreePtr2(p2);
cout<<"after call freePtr2"<<endl;
if(p2 != NULL)
{
cout<<"*p2="<<*p2<<endl;
}
else
{
cout<<"the p2 is null"<<endl;
}
cout<<"---------------------------------------"<<endl;
int *p3 ;
p3 = new int(3);
cout<<"*p3="<<*p3<<endl;
FreePtr3(&p3);
cout<<"after call freePtr3"<<endl;
if(p3 != NULL)
{
cout<<"*p3="<<*p3<<endl;
}
else
{
cout<<"the p3 is null"<<endl;
}
cout<<"---------------------------------------"<<endl;
system("pause");

}
#include <iostream>
using namespace std;
void FreePtr1(int* ptr1)
{
delete ptr1;
ptr1 = NULL;
}
void FreePtr2(int*& ptr2)
{
delete ptr2;
ptr2 = NULL;
}
void FreePtr3(int **ptr3)
{
delete *ptr3;
*ptr3 = NULL;
}
void main()
{
cout<<"---------------------------------------"<<endl;
int *p1 = new int;
*p1 = 1;
cout<<"*p1="<<*p1<<endl;
FreePtr1(p1);
cout<<"after call freePtr1"<<endl;
if(p1 != NULL)
{
cout<<"p1 is not null"<<endl;
cout<<"*p1="<<(*p1)<<endl;
}
cout<<"---------------------------------------"<<endl;
int *p2 = new int;
*p2 = 2;
cout<<"*p2="<<*p2<<endl;
FreePtr2(p2);
cout<<"after call freePtr2"<<endl;
if(p2 != NULL)
{
cout<<"*p2="<<*p2<<endl;
}
else
{
cout<<"the p2 is null"<<endl;
}
cout<<"---------------------------------------"<<endl;
int *p3 ;
p3 = new int(3);
cout<<"*p3="<<*p3<<endl;
FreePtr3(&p3);
cout<<"after call freePtr3"<<endl;
if(p3 != NULL)
{
cout<<"*p3="<<*p3<<endl;
}
else
{
cout<<"the p3 is null"<<endl;
}
cout<<"---------------------------------------"<<endl;
system("pause");
}结果:

comments:
对p1指针:
cout<<"---------------------------------------"<<endl;
int *p1 = new int;
*p1 = 1;
cout<<"*p1="<<*p1<<endl;

// FreePtr1(p1);
void FreePtr1(int* ptr1)
{

delete ptr1;

ptr1 = NULL;

}

cout<<"after call freePtr1"<<endl;
if(p1 != NULL)
{
cout<<"p1 is not null"<<endl;
cout<<"*p1="<<(*p1)<<endl;
}
cout<<"---------------------------------------"<<endl;
而p2为:
调用前:

调用后:

本文通过三个不同的示例介绍了如何在 C++ 中正确地释放动态分配的内存。示例展示了三种释放指针所指向内存的方法,并强调了在操作完成后将指针设置为 NULL 的重要性。
257

被折叠的 条评论
为什么被折叠?



