[問題] vector刪除問題

作者: amy10062003 (徘徊在抉擇之間)   2016-12-14 22:07:58
開發平台(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方式
謝謝
作者: Sirctal (母豬母豬 夜裡哭哭)   2016-12-14 23:16:00
你都會auto了 怎麼不用range loop...而且可以改用 smart_pointer阿...
作者: taies (akira)   2016-12-15 02:39:00
兩個都要用 1刪A 2刪point 先2在12怪怪的 delete *itr?
作者: steve1012 (steve)   2016-12-15 09:08:00
沒規定要用raw pointer 的話就用smart pointer 吧大大
作者: Sirctal (母豬母豬 夜裡哭哭)   2016-12-15 20:41:00
另外問原PO 你這種方式是要實作Observer design pattern?goo.gl/MtzcrP 這邊有類似你的應用 你可以看一下人家怎麼釋放記憶體的
作者: amy10062003 (徘徊在抉擇之間)   2016-12-15 23:29:00
好的 謝謝 再研究一下
作者: hunandy14 (Charlott.HonG)   2016-12-18 14:48:00
都vec了就vec吧,刻意使用vec模擬嗎QQde [] 配 new [] 沒有方括配沒有方括

Links booklink

Contact Us: admin [ a t ] ucptt.com