Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在';上增压ptr#U容器泄漏;发布';?_C++_Boost_Valgrind_Boost Ptr Container - Fatal编程技术网

C++ 在';上增压ptr#U容器泄漏;发布';?

C++ 在';上增压ptr#U容器泄漏;发布';?,c++,boost,valgrind,boost-ptr-container,C++,Boost,Valgrind,Boost Ptr Container,我假设从ptr\u集合释放的对象如果没有手动删除,就会泄漏。但是,下面的测试程序仅显示valgrind中有2处泄漏(来自第9/13行),而第12行没有泄漏。我是否误解了发布,或者ptr\u容器是否设法清理 #include <iostream> #include <boost/ptr_container/ptr_set.hpp> typedef boost::ptr_set<int> SetInt; int main() { SetInt s;

我假设从
ptr\u集合
释放的对象如果没有手动删除,就会泄漏。但是,下面的测试程序仅显示valgrind中有2处泄漏(来自第9/13行),而第12行没有泄漏。我是否误解了
发布
,或者
ptr\u容器
是否设法清理

#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";
}

正如你所观察到的,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不要这样做

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