我有以下示例来释放 STL 向量中的对象。
#include <map>
#include <string>
using namespace std;
class Test
{
   public:
      char*  name;
      int id;
      Test(char* n, int i);
};
Test::Test(char* n, int i)
{
   name = n;
   id = i;
}
int main ()
{
        Test* t = new Test("hi", 5);
        vector<Test> v;
        v.insert(v.end(), *t);
        for(vector<Test>::iterator it = v.begin(); it != v.end(); it++)
        {
                if (it->id == 5)
                {
                        Test* ptr = &*it;
                        v.erase(it);
                        delete ptr;
                        break;
                }
        }
        return 0;
}
根据我一直在研究的内容,这应该是正确的方法。但是,valgrind 给了我这样的抱怨:
==7404== Invalid free() / delete / delete[]
==7404==    at 0x4A05130: operator delete(void*) (vg_replace_malloc.c:244)
==7404==    by 0x400FD2: __gnu_cxx::new_allocator<Test>::deallocate(Test*, unsigned long) (new_allocator.h:94)
==7404==    by 0x401004: std::_Vector_base<Test, std::allocator<Test> >::_M_deallocate(Test*, unsigned long) (stl_vector.h:133)
==7404==    by 0x401045: std::_Vector_base<Test, std::allocator<Test> >::~_Vector_base() (stl_vector.h:119)
==7404==    by 0x40109C: std::vector<Test, std::allocator<Test> >::~vector() (stl_vector.h:272)
==7404==    by 0x400998: main (test.cc:46)
==7404==  Address 0x4C58070 is 0 bytes inside a block of size 16 free'd
==7404==    at 0x4A05130: operator delete(void*) (vg_replace_malloc.c:244)
==7404==    by 0x40098A: main (test.cc:41)
并且存在内存泄漏。这样做的正确方法是什么?