Reference Counting(引用计数): 每个对象都设置一个参数，就是引用它的变量，引用少一个就减1，多一个就加1，为0时回收
Reachability(可达性):有一组基本的对象或变量是可达的，称为root set，这些变量或对象指向的对象也是可达的，同理，一个可达对象指向的对象是可达的。

## Reference Counting

```template <class T> class SmartPointer {
protected:
T* ref;
unsigned int * ref_count;
public:
SmartPointer(T *ptr)
{
ref = ptr;
ref_count = (unsigned int*)malloc(sizeof(unsigned int));
*ref_count = 1;
}
SmartPointer(SmartPointer<T> & sptr)
{
ref = sptr.ref;
ref_count = sptr.ref_count;
++*ref_count;
}
SmartPointer<T> & operator= (SmartPointer<T> &sptr)
{
if(this != &sptr)
{
ref = sptr.ref;
ref_count = sptr.ref_count;
++*ref_count;
}
return *this;
}
~SmartPointer()
{
--*ref_count;
if(*ref_count == 0)
{
delete ref;
free(ref_count);
ref = NULL;
ref_count = NULL;
}
}
T getValue() {return *ref;}
}```

## Mark and Sweep

Mark and Sweep使用的是可达性。在一个程序中，所有的全局变量，静态变量，局部变量都是可达的，这些称为root set。从root出发，找到所有可达的，然后回收不可达的。

Boehm挺好用的，下面是一个例子。

```#include <stdio.h>
#include <gc/gc.h>
int main()
{
int i;
GC_INIT();
int *p;
for(i = 0; i < 1000000; i++)
{
p = (int*)GC_MALLOC(20*1024*1024);
p[i/400] = 5;
if(i % 10000 == 0)
printf("Heap size = %d\n",GC_get_heap_size());
}
}```

## Semispace

```copy(p):
if(content of p is already copy to ToSpace)
ret
if(content of p is not copied to ToSpace)
copy content of p to ToSpace
ToSpacePtr += sizeof(p)
foreach pointer x in content of p:
copy(x)```

## Generation Garbage Collection

```if(G0 is almost full)
{
scan and reclaim G0
if(G1 is almost full)
{
scan and reclaim G1
if(G2 is almost full)
scan and reclaim G2
move survivors to G2
}
move survivors to G1
}```

## 参考

http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)

http://www.memorymanagement.org/glossary/t.html

http://www.hpl.hp.com/personal/Hans_Boehm/gc/

http://xtzgzorex.wordpress.com/2012/10/11/demystifying-garbage-collectors/