[C++-sig] wrapping a reference counted class

Nathan Cournia cournia at gmail.com
Wed Jun 23 06:13:34 CEST 2010


I'm trying to wrap the following class:

class Node
    virtual ~Node();
    virtual void compute();
    void incRef();
    void decRef();

    unsigned _refCount

As you can see, the class is reference counted.  In most places in my
code, I pass around Node* pointers.  I rarely call incRef() and
decRef() to avoid overhead.  I only call incRef() and decRef() in
places where they are absolutely needed.  For instance:

  void addNode(Node* n)

stores a pointer to n and calls n->incRef().  Likewise:

  void remNode()

removes its copy of the Node pointer and calls n->decRef().


  Node* getNode()

Returns a pointer to the Node stored by addNode().  It does _not_ call

Now, let's say I wrapped the three functions above with Boost.Python.
I'm looking for the following reference counting behavior when doing
the following in Python:

0>> x = Node()        # refs = 1
1>> addNode(x)       # refs = 2
2>> y = getNode()    # refs = 3
3>> del x                # refs = 2
4>> del y                # refs = 1
5>> remNode()        # refs = 0

How do I wrap Node such that I get the reference counting behavior
above?  I took a look at:


but at first glance it doesn't appear to be what I want.  I'm not
using smart pointers, instead I'm manually incrementing and
decrementing the reference count.

Thanks in advance for any help.


More information about the Cplusplus-sig mailing list