Iray Programmer's Manual

Reference counting

Interfaces implement reference counting for life-time control.

Whenever a function returns a pointer to mi::base::IInterface or a subclass thereof, the corresponding reference counter has already been increased by 1. That is, you can use the interface pointer without worrying whether the pointer is still valid. Whenever you do not need an interface any longer, you have to release it by calling its release() method. Omitting such calls leads to memory leaks.

In more detail, the rules for reference counting are as follows:

  • A method that returns an interface increments the reference count for the caller. The caller needs to release the interface when it is done.
  • When a caller passes an interface as method argument the caller has to guarantee that the interface is valid for the runtime of that method, and the callee can safely use the interface for that time without the need to change the reference count.
  • If the callee wants to reference an interface passed as an argument later (typically via a member variable) then it has to use reference counting to ensure that the interface remains valid.
  • The initial reference count after construction is 1 (such that one can implement methods returning an interface pointer by writing return new Foo(); ).
  • Interfaces passed as out arguments of methods are treated similar to return values. The callee decrements the reference count for the value passed in and increments it for the value passed back.

See also Handle class.