Suppose you have a Collection<B>
, and you're about to remove an item. Instance of B
is referenced from an instance of A
, and references an instance of C
, as shown in the first picture:
Now, since there was a reference pointing to B, there's no question about the object being "deleted", or garbage collected. It simply gets removed from the collection, like this, right?
Now, let's have a Collection<A>
with the same referencing hierarchy as before, and let's remove an instance of A.
If there's no other reference to A
, not only it gets removed from the collection, it is marked as garbage. Am I right? And what about B
and C
? Do they become garbage too, provided there's no other references except B
referencing an instance of C
?
This is a simplification of what I'm facing. I want to remove an A
instance from a collection and I want to make sure B
and C
go with it. At the point where A
is no longer in my collection, all the "children" that are still alive are a memory leak for me.
When I look at these pictures I made, it seems too stupid of a question. But my situation is a little less trivial. It looks something like this:
- In the picture, Model layer is yellow, ViewModel layer is green
- The 'A ViewModel' class references its
A Model
- The
A Model
has a collection ofB Model
instances (B
is kind of the child ofA
, both in Model and ViewModel layers) - each
B Model
"knows its parent' - references its parent 'A Model' instance - back to VM layer, the 'A ViewModel' holds a collection of 'B ViemModel' items
- as any good ViewModel, 'B ViewModel' references 'B Model'
I have a Collection of those A ViewModel
instances. When I delete one, I need everything other to go with it. Provided there's no other "outside reference" to any of the instances involved (basically, no other arrow pointing coming in from outside of the picture), will the removed 'A ViewModel' instance take all the children with it? If so, are there any "gotchas" that could make this simplification misleading? And if I'm completely wrong, why? :)
Thanks for reading this far!