我尝试释放由STL列表的指针项指向的内存.
这应该工作正常,但在我的情况下,列表中可能有重复的指针,我得到一个双dealloc异常,即使我测试指针是否为NULL(请参阅下面的源代码).我怎么解决这个问题 ?
list<Line *> * l = new list<Line *>;
Line * line = new Line(10, 10, 10, 10);
l->push_back(line);
l->push_back(line);
cout << "line addr " << line << endl;
for (list<Line *>::iterator it = l->begin(); it != l->end(); it++)
 {
  if (*it != NULL)
   {
    cout << "line it " << *it << " " << (*it)->toString() << endl;
    delete (*it);
    (*it) = NULL;
   }
 }
l->clear();
*** glibc detected *** /home/debian/workspace/Scrap/Release/Scrap: double free or corruption (!prev): 0x0846de20 ***
======= Backtrace: =========
/lib/i686/cmov/libc.so.6[0xb6d68764]
/lib/i686/cmov/libc.so.6(cfree+0x96)[0xb6d6a966]
/usr/lib/libstdc++.so.6(_ZdlPv+0x21)[0xb6f402e1]
/home/debian/workspace/Scrap/Release/Scrap[0x8067cb0]
/lib/i686/cmov/libc.so.6(__libc_start_main+0xe5)[0xb6d10455]
/home/debian/workspace/Scrap/Release/Scrap(_ZNSt8ios_base4InitD1Ev+0x49)[0x8052cd1]
======= Memory map: ========
08048000-0842c000 r-xp 00000000 08:01 3819374 /home/debian/workspace/Scrap/Release/Scrap
0842c000-08451000 rw-p 003e3000 08:01 3819374 /home/debian/workspace/Scrap/Release/Scrap
你可以使用智能指针而不是原始指针吗?我会尝试使用boost shared_ptrs,如下所示:
#include <boost/shared_ptr.hpp>
list< boost::shared_ptr< Line > > l;
boost::shared_ptr< Line > line( new Line( 10, 10, 10, 10 ) );
l.push_back( line );
l.push_back( line );
当列表被销毁时,boost::shared_ptr清理将删除Line对象.