How does weak_ptr work?

shared_ptr uses an extra “counter” object (aka. “shared count” or “control block”) to store the reference count. (BTW: that “counter” object also stores the deleter.) Every shared_ptr and weak_ptr contains a pointer to the actual pointee, and a second pointer to the “counter” object. To implement weak_ptr, the “counter” object stores two different counters: The … Read more

How do events cause memory leaks in C# and how do Weak References help mitigate that?

When a listener attaches an event listener to an event, the source object will get a reference to the listener object. This means that the listener cannot be collected by the garbage collector until either the event handler is detached, or the source object is collected. Consider the following classes: class Source { public event … Read more

Where does the weak self go?

First of all, note that you generally don’t need to worry about retain cycles with DispatchQueue.main.asyncAfter, as the closure will be executed at some point. Therefore whether or not you weakly capture self, you won’t be creating a permanent retain cycle (assuming that tickle.fresh also doesn’t). Whether or not you put a [weak self] capture … Read more

Java: difference between strong/soft/weak/phantom reference

Java provides two different types/classes of Reference Objects: strong and weak. Weak Reference Objects can be further divided into soft and phantom. Strong Weak soft phantom Let’s go point by point. Strong Reference Object StringBuilder builder = new StringBuilder(); This is the default type/class of Reference Object, if not differently specified: builder is a strong … Read more

Weak NSString variable is not nil after setting the only strong reference to nil

tl; dr: The problem is that the string literal never gets released so your weak pointer still points to it. Theory Strong variables will retain the value they point to. Weak variables won’t retain their value and when the value is deallocated they will set their pointer to nil (to be safe). Unsafe unretained values … Read more

Why isn’t my weak reference cleared right after the strong ones are gone?

From the assembly code it can be seen that accessing weakPtr generates a objc_loadWeak call. According to the Clang documentation, objc_loadWeak retains and autoreleases the object and is equivalent to id objc_loadWeak(id *object) { return objc_autorelease(objc_loadWeakRetained(object)); } This (hopefully) explains why both if(strongPtr == weakPtr) … and NSLog(@”weakPtr: %@”, weakPtr); create additional autoreleased references. This … Read more