“释放”时提升ptr_container漏洞?

时间:2012-01-27 12:45:33

标签: c++ boost valgrind boost-ptr-container

如果没有手动删除,我假设从ptr_set释放的对象被泄露。但是,下面的测试程序只显示valgrind中的2个泄漏(来自第9/13行),第12行没有泄漏。我是否误解release,或ptr_container是否设法以某种方式清理?< / p>

#include <iostream>
#include <boost/ptr_container/ptr_set.hpp>

typedef boost::ptr_set<int> SetInt;

int main() {
   SetInt s;

   new int(1);                // leak, reported by valgrind

   s.insert(new int(2));
   s.insert(new int(3));      // leak? not reported by valgrind
   s.insert(new int(4));      // leak, reported by valgrind

   s.erase(s.begin());
   s.release(s.begin());      // release '3'

   SetInt::auto_type old_int1 = s.release(s.begin());
   int *old_int2 = old_int1.release();
   std::cout << '\'' << *old_int2 << "' has been released\n";
}

输出:

'4' has been released

1 个答案:

答案 0 :(得分:2)

3的析构函数确实就像你观察到的一样被调用。原因是s.release返回一个智能指针,该指针将在指针超出范围时删除该对象。那么,你的行:

s.release(s.begin());      // release '3'

类似于写作

{    
   SetInt::auto_type tmp= s.release(s.begin());      // release '3'
} // at this point the '3' is destroyed.

对象4没有被破坏,因为你告诉智能指针old_int1不要这样做。

http://www.boost.org/doc/libs/1_34_0/libs/ptr_container/doc/tutorial.html#new-functions