C++ 复杂结构体的内存管理

2018-10-30  本文已影响0人  QuentinnYANG

说明

C++ 中使用 new 和 delete 进行内存的申请和释放,二者成对出现。使用 new 申请的内存在中,只能通过 delete 释放,而局部变量的内存是静态内存,其存储在中是由内存管理器自动管理的,不需要手动释放。

结构体中成员变量存在指针类型的,其内存释放原则为从里向外,即先释放成员变量内存,再释放结构体指针占用的内存。

由于 C++ 中允许存在构造函数和析构函数,可以使用构造函数对成员数据进行初始化,用析构函数对内存进行清理。析构函数在对结构体内存释放时调用。

实例

struct _STU_FamilyInfo
{
    int nAge;
};
 
struct _STU_StudentINFO
{
    char* pstrName;
    int nAge;
    int nFamilyMember;
    _STU_FamilyINFO* pstuInfo;
    LPVOID lpExtInfo;
 
    //Construction
    _STU_StudentINFO()
    {
        pstrName = NULL;
        nAge = 0;
        nFamilyMember = 0;
        lpExtInfo = NULL;
        pstuInfo = NULL;
    };

    //Destruction
    ~_STU_StudentINFO()
    {
        if(pstrName)
        {
            delete []pstrName;
            pstrName = NULL;
        }
 
        if(pstuInfo)
        {
            delete []pstuInfo;
            pstuInfo = NULL;
        }
    };
};
 
//Initialization & assignment
_STU_StudentINFO* pstuStudent = new _STU_StudentINFO;
pstuStudent->pstrName = "Sunny";
pstuStudent->nAge = 27;
pstuStudent->nFamilyMember = 2;
_STU_FamilyInfo* pstuFamilyMember = new _STU_FamilyInfo[2];
pstuStudent->lpExtInfo = new char[256];
memccpy(pstuStudent->lpExtInfo,"无其他说明",256)
 
 
//Release the memory
if( pstuStudent->lpExtInfo )
{
    delete []pstuStuden->lpExtInfo;
    pstuStudent->lpExtInfo = NULL;
}
 
if(pstuStudent)
{
    delete pstuStudent;
    pstuStudent = NULL;
}
上一篇 下一篇

猜你喜欢

热点阅读