請教一個struct的delete的問題 |
答題得分者是:dllee
|
achillean
一般會員 發表:16 回覆:23 積分:7 註冊:2004-08-13 發送簡訊給我 |
typedef struct Vertex { float x, y, z; } Vertex; typedef struct Face { Face(void) : nverts(0), verts(0) {}; int nverts; Vertex **verts; float normal[3]; } Face; typedef struct Mesh { Mesh(void) : nverts(0), verts(0), nfaces(0), faces(0) {}; int nverts; Vertex *verts; int nfaces; Face *faces; } Mesh; Mesh *mesh;我要delete他 if (mesh!=NULL) { delete [] mesh->verts; delete [] mesh->faces; delete mesh; }這樣正確嗎? 發表人 - achillean 於 2004/08/26 22:47:46 |
dllee
站務副站長 發表:321 回覆:2519 積分:1711 註冊:2002-04-15 發送簡訊給我 |
基本上是可以了,但再加一些判斷會更好,如:
if (mesh!=NULL) { if(mesh->verts!=NULL) // 多加判斷 delete [] mesh->verts; if(mesh->faces!=NULL) // 多加判斷 delete [] mesh->faces; delete mesh; mesh=NULL; // 多加設定,即使這個 if(){} 被多次叫用 // 也不會因重覆 delete 而 exception }吃軟也吃硬 dllee.ktop.com.tw 視動科技 VMASK - ViewMove Automation Software Kernel
------
http://www.ViewMove.com |
achillean
一般會員 發表:16 回覆:23 積分:7 註冊:2004-08-13 發送簡訊給我 |
|
dllee
站務副站長 發表:321 回覆:2519 積分:1711 註冊:2002-04-15 發送簡訊給我 |
對不起,經您的提示,才發現之前的 post 還不算完整。不過... 提供以下的 code 給您參考:
typedef struct SelfMaintenance { SelfMaintenance(void) : ABC(NULL), XYZ(NULL) {}; ~SelfMaintenance() { if(ABC!=NULL) delete [] ABC; if(XYZ!=NULL) delete [] XYZ; }; int mno; int opq; int *ABC; double *XYZ; } SelfMaintenance ; typedef struct UseSelfMaintenance { UseSelfMaintenance (void) : OOXX(NULL) { sMaintenance=new SelfMaintenance; }; ~UseSelfMaintenance () { if(OOXX!=NULL) delete [] OOXX; if(sMaintenance!=NULL) delete sMaintenance; }; int *OOXX; SelfMaintenance *sMaintenance; } UseSelfMaintenance ; ... 使用時: UseSelfMaintenance *test=new UseSelfMaintenance; ... 使用後: delete UseSelfMaintenance; 即可,因為所有的記憶體釋放都改在解構元了。這樣自己 new 的自己 delete 如此,就不需要由最上層一直 delete 到最下層。 這樣也才比較像個物件(Object),寫程式也比較簡單。 吃軟也吃硬 dllee.ktop.com.tw 視動科技 VMASK - ViewMove Automation Software Kernel 發表人 - dllee 於 2004/08/27 19:59:12
------
http://www.ViewMove.com |
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |