weak_ptr to break cyclic reference

P

Pallav singh

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
 
M

Marcel Müller

Hi,

Pallav said:
// 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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top