Reference count

from Wikipedia, the free encyclopedia

Under reference count ( English reference counting ) is understood in the programming a technique for managing the number of references ( references or pointers ) to a particular object. The aim is to recognize when an object is no longer needed and can be deleted. Reference counting is one way of automatic garbage collection .

implementation

In order to implement such a reference count, it is necessary to manage a reference counter for each object. It must also be ensured that this counter each additional referencing at establishing increments and upon completion of a referencing decremented is.

If such an approach is implemented consistently , two conditions are always met:

  1. All objects that are still referenced (used) have a counter greater than 0.
  2. All objects with a counter equal to 0 are no longer referenced.

A problem with this technique is cyclic references, i.e. two or more objects that refer to each other. If objects only refer to each other and there is no longer a reference from the outside, i.e. from other objects outside the cycle, the respective reference counters are not 0 and it is not so easy to see that these objects are actually no longer needed. If such a situation cannot be ruled out in principle, there are different algorithms for recognizing such a situation , which are mostly based on the principle of reachability in graphs .

Application examples

Structures and programming environments that operate reference counting:

In programming environments without such automatic memory management, such as C or C ++ , it may be necessary to implement such reference counting yourself if the order of the release of objects cannot be implemented in a predictable and clearly defined order with obvious hierarchical dependencies. In object-oriented languages ​​such as C ++, it is appropriate to encapsulate such a procedure in a class . A typical example is a String class, which ensures that similar content is only created once in the memory and still guarantees that unneeded content is deleted without the programmer having to explicitly worry about it.

See also

Individual evidence

  1. http://gambaswiki.org/wiki/def/gc
  2. https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/AutomaticReferenceCounting.html

literature

  • Scott Meyers; More Effective C ++ ; Addison-Wesley 1996

Web links