2

I'm assuming that an object that's released from a ptr_set is leaked if it's not manually deleted. However, the test program below only shows 2 leaks in valgrind (from lines 9/13), and no leak for line 12. Have I misunderstood release, or is ptr_container managing to clean up somehow?

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

Output:

'4' has been released
EML
  • 1,025
  • 2
  • 9
  • 16

1 Answers1

2

The destructor of 3 is indeed called just as you observed. The reason is that s.release returns a smart pointer which will delete the object when that pointer goes out of scope. So, your line:

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

is similar to writing

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

Object 4 is not destructed because you tell your smart pointer old_int1 not to do it.

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

Johan Lundberg
  • 26,184
  • 12
  • 71
  • 97