1. reference counting
2. mark and sweep
3. copy
2. implementation
In C++, garbage collection with reference counting is almost always implemented with
smart pointers, which perform reference counting.
The main reason for using smart pointers over raw ordinary pointers is the conceptual
simplicity of implementation and usage.
With smart pointers, everything related to garbage collection is performed behind the scenes - typically in constructors / destructors / assignment operator / explicit object mangement functions.
There are two types of functions, both of which are very simple:
RefCountPointer::type1() { //implements depends on reference counting organization // this can also be no ref. counter at all incrementRefCounter(); } RefCountPointer::type2() { // Implementation depends on reference counting organization // there can also be no ref. coutner at all decrementRefcounter(); if ( referenceCounterIsZero() ) destructObject(); } // NOTE Method 1. Simple Reference Counting ( ) struct Object { }; struct RefCount { int count; }; struct RefCountPtr { Object *pointee; RefCount *refCOunt; }; Advantages: performance Disadvantages: memory overhead because of two poitners // NOTE Method 2: Alternative Reference Counting ( ) struct Object { }; struct RefCountPtrImp1 { int count; Object *object; }; struct RefCountPtr { RefCountPtrImp1 * pointee; }; Advantages:no memory overhead because of two pointers Disadvantages: performance penalty extra level of indirection // NOTE Method 3: Intrusive Reference Counting ( ) struct Object { }; struct ObjectIntrusiveReferenceCounting { Object object; int count; }; struct RefCountPtr { ObjectIntrusiveReferenceCounting * pointee; }; Advantages: no previous disadvantage (no overhead due to pointers) Disadvantages: class for intrusive reference counting should be modified // NOTE Method 4: Ownership List Reference Counting (LinkedList) // Ownership list reference counting. It is an alternative for approach // 1-3. For 1-3 it is only important to determine that counter is zero -// its actual is not important. This is the main idea of approached #4 // 1. all smart pointers for given objects are stored in doubly-linked // lists. // 2. The constructor of a smart pointer adds the new node to a list. // 3. The destructor removes a node from the list. // 4. checked if the list is empty or not. If it is empty, the object is // deleted. struct object { }; struct ListNode { Object *pointee; ListNode *next; };3. Similar ones
No comments:
Post a Comment