/*new delete*/

#include "stdafx.h"
#include <stdlib.h>
#include <iostream.h>
#include <string.h>

struct student
{
    student()
    {
        cout << "student::student()" << endl;
    }
    student( char* pStrName )
    {
        cout << "student::student(char*)" << pStrName <<  endl;       
        strcpy(szName,pStrName);
    }
    ~student()
    {
        cout << this << " : student::~student()" << endl;
    }
    void KillMySelf()
    {
        //
这样就析构自己了
        delete this;
    }
    char szName[32];
};

void FunCopyData( char* pChar )

    if ( pChar )
    {
        strcpy( pChar,"Hello");
    }
}

void FunDelPtrRef( char*& pStr )
{
    if ( pStr )
    {
        delete[] pStr;
        pStr = NULL;
    }
}

void FunDelPtrBy2( char** ppStr )
{
    if ( *ppStr )
    {
        delete[] *ppStr;
        *ppStr = NULL;
    }
}

void FunNew()
{
    char *pChar = new char[10];
   
    strcpy( pChar,"New Space");   
    FunCopyData( pChar );   
    //
指针做参数,进行释放,形参设置为0,和实参数没有改变
    //
解决方法 1: 二级别指针解决  2:指针的引用
    FunDelPtrBy2( &pChar );
    FunDelPtrRef( pChar );
}

int main(int argc, char* argv[])
{
    FunNew();
   
    student *p = new student("
张三");
    //
对象数组
    student ObjArray[3] = { "
张三","李四","王五" };   
    //
无参的构造函数构造三个对象
    student *pHeapArray = new student[3];
    //
对象指针数组,与上面个有区别
    student *ObjPtrArray[3] = { new student("
张三"),
                                new student("
李四"),
                                new student("
王五") };
   
    //malloc
不带数据类型,不会有构造函数调用
    //void *p = malloc(sizeof(student));
   
    //
不要破坏堆内存的结构,就是不要越界访问
    //p->szName[32] = 'A';
   
    //[]
成对使用,如果new时有[],那么在delete时也要带上[], new/delete成对使用
    if ( p )
    {
        delete p;
        p = NULL;
    }
   
    for ( int i = 0 ; i < 3 ; i++ )
    {
        if ( ObjPtrArray[i] )
        {
            delete ObjPtrArray[i];
           
            ObjPtrArray[i] = NULL;
        }
    }
   
    if ( pHeapArray )
    {
        delete[] pHeapArray;
        pHeapArray = NULL;
    }
   
    //delete this;
在成员函数中,做2个步骤
    //1.
调用析构 2.释放堆空间
    student * pNewObj = new student;
    //
这样堆空间就没产生
    pNewObj->KillMySelf();
    pNewObj = NULL;
   
    //
在使用delete this的时候,一定要保证后面没有再使用的到这个对象
   
    return 0;
}

posted on 2010-01-21 20:52  o无尘o  阅读(223)  评论(0编辑  收藏  举报