[webkit-dev] Naked new considered harmful

Adam Barth abarth at webkit.org
Tue Aug 24 10:46:35 PDT 2010


One thing Darin and I discussed at WWDC (yes, this email has been a
long time coming) is better programming patterns to prevent memory
leaks.  As I'm sure you know, whenever you allocate a RefCounted
object, you need to call adoptRef to prevent a memory leak by adopting
the object's initial reference:

adoptRef(new FancyRefCountedObject())

We now have an ASSERT that enforces this programming pattern, so we
should be able to catch errors pretty easily.  Recently, Darin also
introduced an analogous function for OwnPtr:

adoptPtr(new NiftyNonRefCountedObject())

What adoptPtr does is shove the newly allocated object into a
PassOwnPtr, which together with OwnPtr, makes sure we don't leak the
object.  By using one of these two functions every time we call new,
it's easy to see that we don't have any memory leaks.  In the cases
where we have an intentional memory leak (e.g., for a static), please
use the leakPtr() member function to document the leak.

In writing new code, please avoid using "naked" calls to new.  If
you're making an object that you expect to be heap-allocated, please
add a "create" method, similar to the create method we use for
RefCounted objects:

static PassOwnPtr<NiftyNonRefCountedObject> create(ParamClass* param)
{
    return adoptPtr(new NiftyNonRefCountedObject(param));
}

You should also make the constructor non-public so folks are forced to
call the create method.  (Of course, stack-allocated objects should
have public constructors.)

I'm going through WebCore and removing as many naked news and I can.
At some point, we'll add a stylebot rule to flag violations for new
code.  If you'd like to help out, pick a directory and change all the
calls to new to use adoptRef or adoptPtr, as appropriate.

Adam


More information about the webkit-dev mailing list