Hi,

(The TL;DR parts are in bold).

This is to draw attention to an important difference in reference counting
between Mozilla (also COM) objects [1] and WebKit (also Blink and Skia)
objects [2]:
- *Mozilla-style objects are created with a refcount of 0* (see e.g. [3],
[4])
- *WebKit-style objects are created with a refcount of 1* (see e.g. [5])

This is important to know for any Mozilla developer writing or reviewing
code that deals with WebKit-style refcounted objects [2]. As long as you're
only dealing with Mozilla-style objects [1] you can safely ignore all of
this.

*Not being aware of this can easily give memory leaks.* For example, look
at typical code like this:

  {
    RefPtr<T> p = new T;
  }

If T is a Mozilla-style reference-counted object, this code is fine: the T
object gets destroyed as p goes out of scope.

But if T is a WebKit-style reference-counted object, this **leaks** !!!
Indeed, the new T starts with a refcount of 1, the RefPtr ups it to 2, and
we're only back to 1 when the RefPtr goes out of scope. In other words, in
WebKit, "new T" implicitly means addref'd even though the type, T*, doesn't
indicate it. Be aware of that, and act accordingly! WebKit's WTF has a
PassRefPtr / adoptRef mechanism [6] that can, IIUC, be used to wrap "new T"
to make it safe in this respect.

Attaching a simple test program demoing this:

bjacob:~$ g++ demoleak.cpp -o demoleak -D USE_MOZILLA_MFBT -I
/hack/mozilla-graphics/obj-firefox-debug/dist/include && ./demoleak
OK, nothing leaked.
bjacob:~$ g++ demoleak.cpp -o demoleak -D USE_WEBKIT_WTF -I
/hack/blink/Source && ./demoleak
leaked 1 object(s)!

So let's be thankful that we have the saner convention (that makes the
above innocuous-looking code actually innocuous), and at the same time
let's be very careful when dealing with imported external code that follows
the other convention!

Cheers,
Benoit

Notes:

[1] By Mozilla/COM style I mean, in particular, anything inheriting
nsISupports or mozilla::RefCounted<T> from MFBT, or using the
NS_*_REFCOUNTING macros from nsISupportsImpl.h.

[2] By WebKit-style I mean anything inheriting WTF's RefCounted<T> or other
similar refcounting mechanisms found throughout WebKit/Blink/Chromium or
related projects e.g. Skia. Of course, I haven't checked everything so I'm
sure that someone will be able to point out an exception ;-)

[3]
http://hg.mozilla.org/mozilla-central/file/d2a7cfa34154/mfbt/RefPtr.h#l63

[4]
http://hg.mozilla.org/mozilla-central/file/d2a7cfa34154/xpcom/glue/nsISupportsImpl.h#l255

[5]
https://github.com/WebKit/webkit/blob/master/Source/WTF/wtf/RefCounted.h#L115

[6] https://github.com/WebKit/webkit/blob/master/Source/WTF/wtf/PassRefPtr.h
_______________________________________________
dev-platform mailing list
dev-platform@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-platform

Reply via email to