Don’t mix objects and interfaces
Posted by jpluimers on 2020/06/11
Worth repeating Dalija Prasnikar, because I bumped into sources of people not getting this concept: [WayBack]: Don’t mix objects and interfaces.
You should not, but sometimes it is hard not to.
The rules in his article are very important as they indicate what’s safe and what’s not:
- object references are weak, interface references are strong
- reference counted object instances need at least one strong reference to keep them alive therefore you can’t use object reference as primary owning reference
- reference counted object instances can be safely accessed through temporary, short-lived (weak) object references, as long as there are strong reference(s) keeping the object alive
So basically:
- ensure a reference counted instance has at least one strong reference to manage the lifetime
- temporary (short-lived) weak references are OK as long as you are sure the strong reference lives longer
Note that unsafe
will make interfaces references weak instead of strong; the same holds for pointer lists [WayBack] Using the [unsafe] attribute, it is possible to store the interface without reference counting. Is there any way for this behavior to be “transferred” … – Jacek Laskowski – Google+
–jeroen
Leave a Reply