From d10e5bbfbfba9698cb33dd4c8cc950cc81d1f626 Mon Sep 17 00:00:00 2001 From: "rick.chan" Date: Fri, 10 Jul 2020 11:34:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20vector=20=E8=A1=A5?= =?UTF-8?q?=E5=85=85=E8=AF=B4=E6=98=8E.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: rick.chan --- .../Cpp_Standard_Library/vector_补充说明.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Software/Development/Library/Cpp_Standard_Library/vector_补充说明.md diff --git a/Software/Development/Library/Cpp_Standard_Library/vector_补充说明.md b/Software/Development/Library/Cpp_Standard_Library/vector_补充说明.md new file mode 100644 index 0000000..c39e84e --- /dev/null +++ b/Software/Development/Library/Cpp_Standard_Library/vector_补充说明.md @@ -0,0 +1,26 @@ +# vector 补充说明 + +## 删除指针成员 + +vector 经常结合对象指针来使用,例如: + +```cpp +class ClassA{ A(){} } + +vector list; +list.push_back(new ClassA()); +``` + +此时调用 erase() 方法后不会 delete 掉 ClassA 的对象。正确释放资源的方法如下: + +```cpp +vector::iterator itr; + +for(itr=list.begin(); itr!=list.end();) +{ + delete (*itr); + list.erase(itr); +} +``` + +这里,end() 指向最后一个元素的下一个位置;调用 delete (*itr) 释放对象;调用 erase() 后,itr 会自动 +1。因此 delete 必须在 erase() 前调用,由于 delete 后,只是析构了对象而没有修改 list 中的成员,因此可以继续调用 list.erase(itr),释放 list 中对应的成员。