09-15-2017 05:09 AM - edited 09-15-2017 05:10 AM
09-17-2017 02:49 PM - edited 09-17-2017 02:51 PM
In theory yes, in practice there are buggy .Net assemblies out there which hand out "property" objects to the caller without those objects referencing their owner in any proper way but still maintaining some pointers that are owned by the owner. Releasing the owner before the owned object could then mean that the the owned object tries to reference something in the owner which has already vanished from memory. So I make it a rule to always close ActiveX and .Net objects in the reverse order in which I obtained them.
Note that you will only get this really bad behavior if there is an actual unsafe pointer (not a normal CLR reference) involved or there is code written to deliberately deviate from the idea of GC (for example; deliberately passing by reference and then nulling references). Otherwise if an object has a root that is not eligible for collection then it too will be ineligible.
In fact the CLR GC is notoriously cautious about this - an example of this is event handlers; when a caller registers to an event the delegate also includes a pointer to the caller. If the caller goes out of scope then it is not eligible for GC as it is still referenced through the delegate to object with the list of event handlers; it will remain in memory and its event handlers will be called. This is a common memory leak (forgetting to remove event handlers for the shorter-lived items that register for them) eg. here
09-18-2017 07:55 AM - edited 09-18-2017 07:56 AM
I'm sure .Net is better in that respect. ActiveX was a real mess about knowing when you had to Release() an object and when not. There were rules but they were violated frequently by component developers and even MS messed up every now and then.
09-18-2017 03:09 PM
Memory management has always been a hard problem; ref counting has weaknesses (like accidental early release) but is so much computationally simpler than maintaining and re-building object trees in memory (which can often go the other way and lead to slow leaks). No model is perfect in my opinion, despite what some naysayers might say.