Why weak_ptr is needed?

I understand below:
1. weak_ptr created as a copy of shared_ptr.
2. weak_ptr provides the access to the referenced object that is owned by one or more shared_ptr instances but it will not take part in reference count.
3. It must be converted to shared_ptr in order to use/access underlying object.

e.g.
1
2
3
4
5
6
7
8
9
10
11
shared_ptr<Adjacent> sp1(new Adjacent());
weak_ptr<Adjacent> wp1 = sp1;

// To access the object via weak_ptr
shared_ptr<Adjacent> sp2 = wp1.lock();

if(!wp1.expired())
{
  // access weak ptr
  sp2->fun1();
}


If shared_ptr object have cyclic dependency
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Adjacent
{
  shared_ptr<ManageIP> sp;
  ManageIP()
  {
    cout<<"Constructor"<<endl;
  }
  ManageIP()
  {
     cout<<"Destructor"<<endl;
  }
  void setAdjacent(shared_ptr<Adjacent> sp1)
  {
     sp = sp1;
  }
};

int main()
{
  shared_ptr<Adjacent> sp1(new Adjacent());
  shared_ptr<Adjacent> sp2(new Adjacent());

  sp1.setAdjacent(sp2);
  sp2.setAdjacent(sp1);
}

Actual Output:
Constructor
Constructor

Expected Output:
Constructor
Constructor
Destructor
Destructor

As there is cyclic dependency of shared_ptr Destructor not gets called.

We can avoid cyclic dependency by declaring data member Adjacent::sp
as a weak_ptr instead of shared_ptr.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Adjacent
{
  weak_ptr<ManageIP> sp;
  ManageIP()
  {
    cout<<"Constructor"<<endl;
  }
  ManageIP()
  {
     cout<<"Destructor"<<endl;
  }
  void setAdjacent(shared_ptr<Adjacent> sp1)
  {
     sp = sp1;
  }
};
Was there a question?
The OP answered his own question, maybe, so nothing else needs to be said since the topic was green-ticked as completed.

Looks like someone is trying to boost their post count.
Topic archived. No new replies allowed.