weak_ptr to break cyclic reference

Discussion in 'C++' started by Pallav singh, Apr 28, 2009.

  1. Pallav singh

    Pallav singh Guest

    Hi All

    How to use weak_ptr to break cyclic reference here ?

    #include <iostream>
    #include <boost/smart_ptr.hpp>
    using namespace std;

    struct Dad;
    struct Child;

    typedef boost::shared_ptr<Dad> DadPtr;
    typedef boost::shared_ptr<Child> ChildPtr;


    struct Dad
    {
    ChildPtr myBoy;
    };

    struct CChild
    {
    DadPtr myDad;
    };

    // a "thing" that holds a smart pointer to another "thing":
    DadPtr parent(new DadPtr);
    ChildPtr child(new ChildPtr);

    // deliberately create a circular reference:
    parent->myBoy = child;
    child->myDad = dad;

    Thanks
    Pallav Singh
     
    Pallav singh, Apr 28, 2009
    #1
    1. Advertising

  2. Hi,

    Pallav singh wrote:
    > // a "thing" that holds a smart pointer to another "thing":
    > DadPtr parent(new DadPtr);
    > ChildPtr child(new ChildPtr);
    >
    > // deliberately create a circular reference:
    > parent->myBoy = child;
    > child->myDad = dad;


    If your child objects have an existence dependency on their parents you
    can safely use a weak pointer from child to parent.


    Marcel
     
    Marcel Müller, Apr 28, 2009
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Raf256
    Replies:
    1
    Views:
    2,228
    Howard Hinnant
    Apr 19, 2005
  2. Goran
    Replies:
    1
    Views:
    557
    mlimber
    Oct 24, 2005
  3. =?UTF-8?B?UmFmYcWCIE1haiBSYWYyNTY=?=

    boost::weak_ptr and shared_ptr pointers from "this"

    =?UTF-8?B?UmFmYcWCIE1haiBSYWYyNTY=?=, Apr 5, 2006, in forum: C++
    Replies:
    2
    Views:
    1,243
    Joe Gottman
    Apr 6, 2006
  4. Alan Johnson

    How to check if a weak_ptr is empty?

    Alan Johnson, May 20, 2006, in forum: C++
    Replies:
    7
    Views:
    4,365
    Pete Becker
    May 21, 2006
  5. Christopher
    Replies:
    2
    Views:
    1,953
    Joe Gottman
    Feb 4, 2009
Loading...

Share This Page