Encyclopedia > Weak reference

  Article Content

Weak reference

Weak reference is an object-oriented programming term. It refers to a reference to an object that does not hold that object in memory. The object to which a weak reference points can be removed by the garbage collector at any time.

In some programming languages, using a data object required that the programmer reserve some memory for the object before even creating it. After the program was done with the data object, it had to explicitly free the memory previously reserved for it, or that memory would have staid reserved for an object that is no longer referenced in the program and was therefore wasted. Problems like these are called memory leaks.

In modern dynamic programming languages, like Python, memory is reserved for objects automatically and is kept as long as the object is being referenced in the application. Once the object is not being referenced anywhere in the applications, a garbage collection system can automatically destroy it and free the memory it is using.

Still, in these programming langauges, effective memory leaks can still happen if an object is not being referenced while it is not needed or used anymore in the application. In some cases, applications want to keep references to objects only as long as they are being referenced somewhere else. This is what is called a weak reference. A weak reference can point to the object, but will not prevent garbage collection if aren't any other (non-weak) references to the object.

One example of how a weak reference can be useful is keeping track of the current variables being referenced in the application. This list must have weak links to the objects. Otherwise, once objects are added to the list, they will be referenced by it and will persist forever (or until the program stops).



All Wikipedia text is available under the terms of the GNU Free Documentation License

 
  Search Encyclopedia

Search over one million articles, find something about almost anything!
 
 
  
  Featured Article
Westhampton Beach, New York

... of 7.7 km² (3.0 mi²). 7.5 km² (2.9 mi²) of it is land and 0.2 km² (0.1 mi²) of it is water. The total area is 2.35% water. Demographics ...

 
 
 
This page was created in 25.2 ms