Boost logo

Boost :

From: Lorenzo Bettini (bettini_at_[hidden])
Date: 2005-06-06 08:58:41


Hi

I have this simple program, that has a class with a shared pointer to
another object of the same type:

#include <boost/shared_ptr.hpp>
#include <string>
#include <iostream>

using namespace std;

class C;

typedef boost::shared_ptr<C> CP;

class C
{
private:
   string s;
   CP cp;

public:
   C(const string &ss, CP c = CP()) : s(ss), cp(c) {}
   void set(CP c) { cp = c; }
   ~C() { cout << "deleting C" << endl; }
};

int
main()
{
   CP cp = CP(new C("C"));
   CP cp2 = CP(new C("C2"));
   cp->set(cp2);
   //cp->set(cp);
   cout << "use_count: " << cp.use_count() << endl;;

   return 0;
}

if I remove the comment for cp->set(cp), i.e., I set the shared_pointer
to itself, there's a cycle, and thus use_count returns 2, and the object
  cp is never deleted (shown also by using valgrind).

This is a simple program just to reproduce a much more complex situation
with a data structure that deals with mutual recursive references.

I do not know in advance whether the shared pointer refers to the same
object or to another different object (for instance I perform also
cp->set(cp2)).

Now, the documentation
(http://www.boost.org/libs/smart_ptr/shared_ptr.htm) says that

"Because the implementation uses reference counting, cycles of
shared_ptr instances will not be reclaimed. For example, if main() holds
a shared_ptr to A, which directly or indirectly holds a shared_ptr back
to A, A's use count will be 2. Destruction of the original shared_ptr
will leave A dangling with a use count of 1. Use weak_ptr to "break
cycles.""

However, it is not clear to me how to use weak_ptr in this context...

can some one provide some clue, please?

many thanks in advance
        Lorenzo


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk