c++ - boost 'release' 上的 ptr_container 泄漏?

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

我假设从 ptr_set 释放的对象如果没有手动删除就会泄露。然而,下面的测试程序只显示了 valgrind 中的 2 个泄漏(从第 9/13 行开始),第 12 行没有泄漏。我误解了 release,还是 ptr_container 管理以某种方式清理?

#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

最佳答案

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

关于c++ - boost 'release' 上的 ptr_container 泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9033427/

相关文章:

c - "Use of uninitialised value"尽管有 memset

python - 关于在 Debug模式下编译Python的问题

c++ - 如何在C++中编写通用对象池

c++ - Boost:当缺少类型时,如何通过基指针序列化/反序列化泛型类型集合?

c++ - 执行 writefile 函数两次

c++ - boost 标记图,内部图尺寸错误

c++ - Boost 1.36 与 STLPort 4.6.2 编译错误

c - 从结构体指针数组中删除元素

c++ - 用随机数填充 vector c++

带有自定义键的 C++ 映射