Content deleted Content added
m →Lua |
m Task 70: Update syntaxhighlight tags - remove use of deprecated <source> tags |
||
Line 29:
If a weak reference is created, and then elsewhere in the code <code>get()</code> is used to get the actual object, the weak reference isn't strong enough to prevent garbage collection, so it may be (if there are no strong references to the object) that <code>get()</code> suddenly starts returning null.<ref>https://web.archive.org/web/20110303225354/http://weblogs.java.net/blog/2006/05/04/understanding-weak-references Java Examples</ref>
<
import java.lang.ref.WeakReference;
Line 44:
}
}
</syntaxhighlight>
Another use of weak references is in writing a [[cache (computing)|cache]]. Using, for example, a weak [[hash map]], one can store in the cache the various referred objects via a weak reference. When the garbage collector runs — when for example the application's memory usage gets sufficiently high — those cached objects which are no longer directly referenced by other objects are removed from the cache.
===Smalltalk===
<
|a s1 s2|
Line 66:
ObjectMemory collectGarbage.
a printOn: Transcript. "second element gone"
</syntaxhighlight>
===Lua===
<
weak_table = setmetatable({}, {__mode="v"})
weak_table.item = {}
Line 76:
collectgarbage()
print(weak_table.item)
</syntaxhighlight>
===Objective-C 2.0===
In [[Objective-C]] 2.0, not only garbage collection, but also [[Reference counting|automatic reference counting]] will be affected by weak references. All variables and properties in the following example are weak.
<
@interface WeakRef : NSObject
{
Line 91:
@end
</syntaxhighlight>
The difference between <code>weak</code> (<code>__weak</code>) and <code>unsafe_unretained</code> (<code>__unsafe_unretained</code>) is that when the object the variable pointed to is being deallocated, whether the value of the variable is going to be changed or not. <code>weak</code> ones will be updated to [[Null pointer|<code>nil</code>]] and the <code>unsafe_unretained</code> one will be left unchanged, as a [[dangling pointer]]. The <code>weak</code> references is added to Objective-C since [[Mac OS X Lion|Mac OS X 10.7 "Lion"]] and [[iOS 5]], together with [[Xcode]] 4.1 (4.2 for iOS), and only when using ARC. Older versions of Mac OS X, iOS, and GNUstep support only <code>unsafe_unretained</code> references as weak ones.
===[[Vala (programming language)|Vala]]===
<
class Node {
public weak Node prev; // a weak reference is used to avoid circular references between nodes of a doubly-linked list
public Node next;
}
</syntaxhighlight>
===Python===
<
>>> import weakref
>>> import gc
Line 121:
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'spam'
</syntaxhighlight>
== See also ==
|