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.