Reference Counting

Reference Counts

To manage the lifetime of objects, Panda3D has a reference counting system for many objects. This means that for every object that uses this mechanism, a reference count is kept which counts the number of references exist to that object. Every time a new reference is made (eg. assigned to a new variable), the reference count is increased. When the reference count reaches zero, the object is deleted.

This is similar to Python’s reference counting system, and in fact, the two systems interact when Panda3D is used with Python. However, since an object’s lifetime may persist beyond the lifetime of an object in Python, Python’s own reference counting system alone is not sufficient.

Since this system is entirely integrated with Python’s own reference counting system, you generally do not need to be concerned with the details of this system. This page only exists for advanced users who need to manipulate the reference count for low-level integration with C++ code.

The class that manages the reference count is ReferenceCount. To see if a class is reference counted, check if it inherits from ReferenceCount. C++ classes that are reference counted inherit from either ReferenceCount or TypedReferenceCount (if use of the typing system is desired), or another class that itself inherits from ReferenceCount.

Managing Reference Counts

There are several ways that the reference count can be manipulated in code. To get the number of references to an object, use the get_ref_count() method.

The reference counted can be incremented and decremented manually using the ref() and unref() methods, but be careful! This messes up Panda’s internal bookkeeping, and will likely cause crashes and memory leaks. Do not do this unless you know exactly what you’re doing!