Using Weak References

From Apache OpenOffice Wiki
Jump to: navigation, search



The C++ binding offers a method to hold UNO objects weakly, that is, not holding a hard reference to it. A hard reference prevents an object from being destroyed, whereas an object that is held weakly can be deleted anytime. The advantage of weak references is used to avoid cyclic references between objects.

An object must actively support weak references by supporting the com.sun.star.uno.XWeak interface. The concept is explained in detail in chapter Lifetime of UNO objects.

Weak references are often used for caching. For instance, if you want to reuse an existing object, but do not want to hold it forever to avoid cyclic references.

Weak references are implemented as a template class:

  template< class t >
  class com::sun::star::uno::WeakReference<t>

You can simply assign weak references to hard references and conversely. The following examples stress this:

  // forward declaration of a function that 
  Reference< XFoo > getFoo();
 
  int main()
  {
      // default construct a weak reference.
      // this reference is empty
      WeakReference < XFoo > weakFoo;
      {
          // obtain a hard reference to an XFoo object
          Reference< XFoo > hardFoo = getFoo();
          assert( hardFoo.is() );
 
          // assign the hard reference to weak referencecount
          weakFoo = hardFoo;
 
          // the hardFoo reference goes out of scope. The object itself
          // is now destroyed, if no one else keeps a reference to it.
          // Nothing happens, if someone else still keeps a reference to it
      }
 
      // now make the reference hard again
      Reference< XFoo > hardFoo2 = weakFoo;
 
 
      // check, if this was successful
      if( hardFoo2.is() )
      {
          // the object is still alive, you can invoke calls on it again
          hardFoo2->foo();
      }
      else
      {
          // the object has died, you can't do anything with it anymore.
      }
  }

A call on a weak reference can not be invoked directly. Make the weak reference hard and check whether it succeeded or not. You never know if you will get the reference, therefore always handle both cases properly.

It is more expensive to use weak references instead of hard references. When assigning a weak reference to a hard reference, a mutex gets locked and some heap allocation may occur. When the object is located in a different process, at least one remote call takes place, meaning an overhead of approximately a millisecond.

The XWeak mechanism does not support notification at object destruction. For this purpose, objects must export XComponent and add com.sun.star.lang.XEventListener.

Content on this page is licensed under the Public Documentation License (PDL).
Personal tools
In other languages