Circular dependencies/references

Hi guys I am following a tutorial http://www.learncpp.com/cpp-tutorial/15-7-circular-dependency-issues-with-stdshared_ptr-and-stdweak_ptr/ on circular references in relation to shared pointers,but the part that I don't understand is this( the third example of code)

he also says
this We don’t have to worry about circular dependencies with std::shared_ptr variable “partner” since it’s just a local variable inside the function. It will eventually go out of scope at the end of the function and the reference count will be decremented by 1.


why wouldn't this be a circular reference? the shared pointer partner will point to the Lucy object so when the Lucy object goes out of scope and since partner is a shared pointer I thought the lucy object wouldn't be destroyed

he says because partner is a local variable but what does he mean by this? Ricky and Lucy are also local variables to main?

also in the comments he says

[I'm actually talking about the local partner variable in main. At that point, we have 1 shared pointer (partner), and 2 weak pointers (lucy and ricky's m_partner). Local variable partner will go out of scope first. At that point, there are no shared pointers left, so when lucy and ricky go out of scope, there's nothing preventing m_partner from deleting its contents.


but isn't there three shared pointers ?? lucy,ricky and partner??

when does the shared Pointers go out of scope in this example?



thanks


**Code in link **
Last edited on
There are two Person objects and three shared pointers.

When the main function ends the three pointers will get destroyed so there are no longer any shared pointers pointing to the Person objects so they will also get destroyed at this point.
Last edited on
still don't follow,

partner points to Lucy and since its a shared pointer wouldn't this cause a circular dependency?
Last edited on
A points to B and B points to A is circular.
A points to B but nothing points to A is not circular.
 ========       =========  
 |Person|- - - >|Person |
 |object|       |object |
 |"Lucy"|< - - -|"Ricky"|
 ========       =========
   ^  ^               ^
   |  |               |
===|==|===============|====
|  |  | Main function |   |
|  | lucy           ricky |
| partner                 |
===========================


As you can see, the only circle you have here is between the two Person objects, but that is handled by using weak pointers instead of shared pointers.
Last edited on
Topic archived. No new replies allowed.