My Octopress Blog

A blogging framework for hackers.

Week Reference - What Is It and How to Use It ?

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "nsWeakPtr.h"
#include "nsIWeakReferenceUtils.h"
// ...

// it's easy to get a weak reference...
nsWeakPtr weakPtr = do_GetWeakReference(aFooPtr);

// ...

{   // ...but to use my weak reference, I'll need a (short-lived) owning reference
  nsCOMPtr<nsIFoo> tempFooPtr = do_QueryReferent(weakPtr);
  if ( tempFooPtr )
    tempFooPtr->SomeFooMethod(...);
  // else, the `real' object has gone away
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class nsObservable
  {
    public:
      // ...
      nsresult AddObserver( nsIObserver* );
      nsresult NotifyObservers( nsIMessage* );
      // ...
    private:
      nsWeakPtr mObserver;
      // ...or imagine a list of observers here
  };

// ...

nsresult
nsObservable::AddObserver( nsIObserver* aObserver )
  {
    mObserver = getter_AddRefs( NS_GetWeakReference(aObserver) );
      // ...or append this to the list of observers
    return NS_OK;
  }

nsresult
nsObservable::NotifyObservers( nsIMessage* aMessage )
  {
    nsCOMPtr<nsIObserver> observer = do_QueryReferent(mObserver);
    if ( observer )
      observer->NoticeMessage(aMessage);
    else
      mObserver = 0;
      // or remove this observer from the list, he's gone away
    return NS_OK;
  }

// ...