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

Pros and Cons of Listeners as WeakReferences

First of all, using WeakReference in listeners lists will give your object different semantic, then using hard references. In hard-reference case addListener(…) means “notify supplied object about specific event(s) until I stop it explicitly with removeListener(..)”, in weak-reference case it means “notify supplied object about specific event(s) until this object will not be used by … Read more

What is the difference between a __weak and a __block reference?

From the docs about __block __block variables live in storage that is shared between the lexical scope of the variable and all blocks and block copies declared or created within the variable’s lexical scope. Thus, the storage will survive the destruction of the stack frame if any copies of the blocks declared within the frame … Read more

Understanding Java’s Reference classes: SoftReference, WeakReference, and PhantomReference

The Java library documentation for the java.lang.ref package characterizes the decreasing strength of the three explicit reference types. You use a SoftReference when you want the referenced object to stay alive until the host process is running low on memory. The object will not be eligible for collection until the collector needs to free memory. … Read more

Why can the keyword “weak” only be applied to class and class-bound protocol types

One common reason for this error is that you have declared you own protocol, but forgot to inherit from AnyObject: protocol PenguinDelegate: AnyObject { func userDidTapThePenguin() } class MyViewController: UIViewController { weak var delegate: PenguinDelegate? } The code above will give you the error if you forget to inherit from AnyObject. The reason being that … 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

Is it possible to create a “weak reference” in JavaScript?

Update: Since July, 2020 some implementations (Chrome, Edge, Firefox and Node.js) has had support for WeakRefs as defined in the WeakRefs proposal, which is a “Stage 3 Draft” as of December 16, 2020. There is no language support for weakrefs in JavaScript. You can roll your own using manual reference counting, but not especially smoothly. … Read more