I known how weak_ptr
is used, I read the following post:
About “circular reference”, I used weak_ptr but memory leak still happened
But there is a concept I can't understand yet.
I will demonstrate shared_ptr
's created and released as I understand it:
1. shared_ptr
pa
created
reference_count
of pa
should be 0
.
Because no shared_ptr
points to pa
.
{/*scope 1*/
shared_ptr<int> pa;
// reference_count_pa = 0
}
2. I assign new shared_ptr<int>
pb
to pa
in another scope
{/*scope 1*/
shared_ptr<int> pa;
{/*scope 2*/
shared_ptr<int> pb = pa;
// reference_count_pa = 1
// reference_count_pb = 0
}
}
reference_count
of pa
should be 1
because shared_ptr
pb
points to pa
.
reference_count
of pb
should be 0
because no shared_ptr
points to pb
.
3. Now, a simple Circular Reference
:
as is demonstrated in About “circular reference”, I used weak_ptr but memory leak still happened:
{/*scope 1*/
shared_ptr<int> pa;
{/*scope 2*/
shared_ptr<int> pb = pa;
pa = pb; //circular reference
// reference_count_pa = 1
// reference_count_pb = 1
}
}
reference_count
of pa
should be 1
because shared_ptr
pb
points to pa
reference_count
of pb
should be 1
because shared_ptr
pa
points to pb
4. In the end of scope 2
pb
is deleted because program walks out of scope 2
.
reference_count
of pa
is 0
now, because no shared_ptr
points to pa
.
reference_count
of pb
is still 1
.
5. In the end of scope 1
reference_count
of pb
is 0
now because no shared_ptr
points to pb
.
The above steps are the reference_count as I understand it.
pa
and pb
are being deleted normally.
I'm confused.
Can anyone correct my error in the above steps?
Thanks!