Reference counting

G

Gianni Mariani

Hi
Cn any one telll me what is Reference counting in C++.

Reference counting usually means that dynamically created objects
maintain a "reference count" that counts the number of "owners" or said
another way the number of times the reference count needs to be
decremented so as to indicate to the last "owner" that it is responsible
to dispose of the dynamically created object.

Reference counted systems usually go hand in hand with "smart pointers"
where each smart pointer contains an obligation of "ownership". The
destructor and assignment operators of the "smart pointer" are
overloaded so that when the smart pointer is deleted or assigned it will
decrement the "reference count".

This is a simplistic form of automated "garbage collection" but suffers
a design constraint that there must be no loops in your "ownership
graph" otherwise it will leak.

There are many systems that employ a reference counting technique. e.g.
Win32 COM has an abstract base class that an "AddRef()" and "Release()"
method. Boost has a smart pointer that employs a reference count for
you named "shared_ptr<>" and will be made part of the next revision of
the C++ standard. You have Loki and Austria libraries that also employ
smart pointers.

In my experience, employing reference counting and smart pointers
results in vast improvements software development.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top