代码改变世界

C++一些基本的内存释放模板

2011-07-24 16:21  bingcaihuang  阅读(936)  评论(0编辑  收藏  举报

1.方法名称:  __delete   (template)
 方法描述:以传入的指针类型,去释放传入的list所包含的所有item.
           传入的类型必须是指针类型,且不能是void*.如果list为空不会出错

template <class T>void __delete(TList* list)
{
    if(list == NULL)
    {
        return;
    }

    for(int i=0; i<list->Count; i++)
    {
        delete (T)list->Items[i];
    }
    list->Clear();
}

2.方法名称:  DeleteStruct
 方法描述:释放结构体所占内存;
 参数:T* tStruct  说明:需要释放的结构体指针

template <class T>void DeleteStruct(T* tStruct)
{
    if(NULL != tStruct)
    {
        delete tStruct;
        tStruct = NULL;
    }
}

3. 方法名称:  FreeLVData
   方法描述:释放ListView及其所占内存;
   参数:TListView * ListView  说明 :需要释放的listview指针

template <class T>void FreeLVData(TListView * ListView)
{
    for(int i = 0; i < ListView->Items->Count; i++)
    {
        delete(T)ListView->Items->Item[i]->Data;
    }
    ListView->Items->Clear();
}

4. 方法名称:  FreeNodeDataMemory
   方法描述:释放TreeNode及其所占内存;
   参数:TTreeNode *paraNode 说明:需要释放的TreeNode指针

template <class T>void FreeNodeDataMemory(TTreeNode *paraNode)
{
    T *tempStruct;
    TTreeNode *tempNode;

    if(false==paraNode->HasChildren)
    {
        return;
    }

    for(int i=0; i < paraNode->Count; i++)
    {
        tempNode=paraNode->Item[i];

        if(NULL != tempNode)
        {
            tempStruct = (T *)tempNode->Data;
            delete tempStruct;
            tempStruct=NULL;
        }
    }

}

5. 方法名称:  FreeGongDantree
   方法描述:释放树及其所占内存;
   参数:TTreeView *tv_GongDan  说明 :需要释放的TreeView指针

template <class T>void FreeGongDantree(TTreeView *tv_Tree)
{
    TTreeNode *tempNode;
    T *tempStruct;
   
    if(0 == tv_Tree->Items->Count)
    {
        return;
    }

    for(int i=0; i < tv_Tree->Items->Count; i++)
    {
        tempNode = tv_Tree->Items->Item[i];
        if((NULL != tempNode)&&(tempNode->Level > 0))
        {
            tempStruct = (T *)tempNode->Data;
            delete tempStruct;
            tempStruct = NULL;
        }
    }
    tv_Tree->Items->Clear();
}

转自:http://blog.sina.com.cn/s/blog_69f519140100l2hs.html