使用弱引用

From Apache OpenOffice Wiki
Jump to: navigation, search



C++ 绑定提供一种弱包含 UNO 对象的方法,即不包含对 UNO 对象的硬引用。硬引用使对象不会被析构,而弱包含的对象可以随时被删除。弱引用的优点是可以用于避免对象之间的循环引用。


对象必须通过支持 com.sun.star.uno.XWeak 接口来主动支持弱引用。专业 UNO - UNO 概念 - UNO 对象的生存期 一节中详细阐述了这一概念。


弱引用通常用于缓存。例如,如果您想重复使用某个现有对象,但不希望永远保留此对象以避免循环引用。


弱引用是作为模板类实现的:

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

您可以简单地将弱引用指定为硬引用,以及将硬引用指定为弱引用。以下示例着重说明了这一点:

 // 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.
     }
 }


不能直接对弱引用进行调用。使弱引用成为硬引用,并检查是否成功。您永远不会知道您是否将获得引用,因此,请始终正确处理两种情况。


使用弱引用比使用硬引用要昂贵一些。将弱引用指定到硬引用时,会锁定某个互斥体,而且可能会进行一些堆分配。当对象处于其他进程中时,至少会进行一次远程调用,这意味着需要耗用大约一毫秒。


XWeak 机制不支持在对象析构时进行通知。为此,对象必须导出 XComponent 并添加 com.sun.star.lang.XEventListener


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