In XPCOM, a weak reference is a special object that contains a pointer to an XPCOM object,
but does not keep that object alive. If the referent object is destroyed before the weak
reference, the pointer inside the weak reference is set to nsnull.
How do I use it?
Here’s an example. The new and interesting things are highlighted.
123456789101112131415
#include "nsWeakPtr.h"#include "nsIWeakReferenceUtils.h"// ...// it's easy to get a weak reference...nsWeakPtrweakPtr=do_GetWeakReference(aFooPtr);// ...{// ...but to use my weak reference, I'll need a (short-lived) owning referencensCOMPtr<nsIFoo>tempFooPtr=do_QueryReferent(weakPtr);if(tempFooPtr)tempFooPtr->SomeFooMethod(...);// else, the `real' object has gone away}
classnsObservable{public:// ...nsresultAddObserver(nsIObserver*);nsresultNotifyObservers(nsIMessage*);// ...private:nsWeakPtrmObserver;// ...or imagine a list of observers here};// ...nsresultnsObservable::AddObserver(nsIObserver*aObserver){mObserver=getter_AddRefs(NS_GetWeakReference(aObserver));// ...or append this to the list of observersreturnNS_OK;}nsresultnsObservable::NotifyObservers(nsIMessage*aMessage){nsCOMPtr<nsIObserver>observer=do_QueryReferent(mObserver);if(observer)observer->NoticeMessage(aMessage);elsemObserver=0;// or remove this observer from the list, he's gone awayreturnNS_OK;}// ...