cs315_refc

This example uses std::tr1::shared_ptr (aka shared pointer), which is a smart pointer in C++, to illustrate how cyclic references result in unreclaimed memory when using reference counting based garbage collection. shared_ptr is a reference counting smart pointer which can automate memory management in C++. Instead of using T *, if we use shared_ptr<T>, then the smart pointer library will handle deallocation of memory automatically, by applying reference counting. When a shared pointer object goes out of scope, it will decrement the reference count and delete the object if the reference count reaches 0. However, when there are cycles involved, some objects cannot be deallocated, even though they are not reachable.

Below is an example illustrating this (using C++98):

#include <tr1/memory>
#include <cstdlib>
#include <iostream>

using namespace std;
using namespace std::tr1;

class Bar;
typedef shared_ptr<Bar> BarPtr;

class Foo;
typedef shared_ptr<Foo> FooPtr;

class Foo
{
public:
    Foo () { cout << "foo created" << endl; }
    ~Foo () { cout << "foo destroyed" << endl; }
    void setBar(BarPtr bar) { bar_ = bar; }
private:
    BarPtr bar_;
};

class Bar
{
public:
    Bar () { cout << "bar created" << endl; }
    ~Bar () { cout << "bar destroyed" << endl; }
    void setFoo(FooPtr foo) { foo_ = foo; }
private:
    FooPtr foo_;
};

int main()
{
    FooPtr foo1(new Foo());
    BarPtr bar1(new Bar());
    FooPtr foo2(new Foo());
    BarPtr bar2(new Bar());

    foo2->setBar(bar2);
    bar2->setFoo(foo2);

    return EXIT_SUCCESS;
}

This will print:

foo created
bar created
foo created
bar created
bar destroyed
foo destroyed
cs315_refc.txt · Last modified: 2013/04/06 16:37 by bgedik

Page Tools