看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) Win7 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) VC++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) std::vector 問題(Question): assign value完之後 最後如何delete 餵入的資料(Input): 會有5個structure A 裡面有一個float 以及另一結構4份資料 預期的正確結果(Expected Output): 資料memory都清空 錯誤結果(Wrong Output): 資料沒有全放掉 程式碼(Code):(請善用置底文網頁, 記得排版) struct point { int X; int Y; }; struct A { float fSpeed; std::vector<point*>pointVec; }; // Assign value A* pA = new A[5]; for(int i = 0 ; i < 5 ; i++) { pA[i]->fSpeed = 2.0; for(int nPointIndex = 0 ; nPointIndex < 4 ; nPointIndex++) { point* pPoint = new point(); pPoint.X = ... pPoint.Y = ... pA[i]->pointVec.push_back(pPoint); } } // Delete Method 1 if(pA) { delete [] pA; pA = NULL; } Method 2 for(int i = 0 ; i < 5 ; i++) { auto itr = pA[i]->pointVec.begin(); for(; itr != pA[i]->pointVec.end(); itr++) { delete &itr; } } 補充說明(Supplement): 以上兩種方法會都清空嗎? 還是有沒有更好的delete方式 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.240.175.113 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1481724480.A.52E.html
Sirctal: 你都會auto了 怎麼不用range loop... 12/14 23:16
Sirctal: 而且可以改用 smart_pointer阿... 12/14 23:19
taies: 兩個都要用 1刪A 2刪point 先2在1 12/15 02:39
taies: 2怪怪的 delete *itr? 12/15 02:40
steve1012: 沒規定要用raw pointer 的話就用smart pointer 吧大大 12/15 09:08
Sirctal: 另外問原PO 你這種方式是要實作Observer design pattern? 12/15 20:41
Sirctal: goo.gl/MtzcrP 這邊有類似你的應用 你可以看一下人家怎麼 12/15 20:42
Sirctal: 釋放記憶體的 12/15 20:42
amy10062003: 好的 謝謝 再研究一下 12/15 23:29
hunandy14: 都vec了就vec吧,刻意使用vec模擬嗎QQ 12/18 14:48
hunandy14: de [] 配 new [] 沒有方括配沒有方括 12/18 14:49