On reference counting

I made a little bit of documentation on reference counting. It’s not yet really finished, but I’ve let two other developers review it now. I guess that means it’s somewhat ready.

The reason I made it was because as I browsed and contributed to GNOME’s code, I noticed that a lot of developers seem to either ignore reference counting or they use it incorrectly all over their code.

I even saw people removing their valid reference usage because they had a memory leak they wanted to solve. As if introducing a race condition is the right fix for a memory leak! Some people have rather strange ways of fixing bugs.

What people who don’t want to care about it should do, and I agree with them, is to use Vala instead.(Or D, or Python, or C#, or Java, before I get hordes of language fans in my comments again. Oh! Or C++ with smartpointers too! – oeps, I almost forgot about the poor céé plus plus guys -)

Anyway, I’m sure my guidelines are not correct according to some people, as there are probably a lot of opinions on reference counting. In general I do think that whenever you pass an instance to another context (another thread or a callback) that you simply must add a reference. If you do this consistently you’ll have far less problems with one context finalizing while another context is still using it.

It’s a wiki page, I’m subscribed. You can just change the content if you disagree. Being subscribed I’ll notice your changes and I’ll review them that way.

http://live.gnome.org/ReferenceCounting

It’s not the first such item that I wrote down. Here are a few others:

After reviewing this document José Dapena promised me he’s going to make a page about reference count debugging in gdb, like adding watches on the ref_count field of instances. To make sure he keeps to his promise I decided to put a note about that here. <g>

3 thoughts on “On reference counting”

  1. Hey Phillip,

    You’re slightly wrong on the cyclic reference counting issue. Gobjects cope pretty well with cyclic reference without using weak references. The important thing is to release all your object’s references in the dispose method. The objects will only be finalized when the whole cycle has been dereferenced (at at least, that’s the theory..)

    Good stuff apart from that though :)

    Rob

  2. I do not understand, Rob. Picture this (X would be some object within the application and the circle is made of A, B and C):
    X-&gt;A-&gt;B-&gt;C-&gt;A
    The reference counts thus are (n for arbitray):
    (n)-&gt;(2)-&gt;(1)-&gt;(1)-&gt;(2)
    When the reference from X to A is released, A remains with count of 1, hence no reason to run dispose and the circle stays intact.

Comments are closed.