[webkit-dev] Using protect(this) versus ref()ing in its caller
Benjamin Poulain
benjamin at webkit.org
Wed Nov 6 14:53:25 PST 2013
On 11/6/13, 2:01 PM, Ryosuke Niwa wrote:
> This discusion came up multiple times on Bugzilla so I'm posting it here.
>
> When a member function f() of a RefCounted object can end up removing
> the last ref to the object itself, should we do:
>
> void Foo::f() {
> RefPtr<Foo> protect(this);
> }
>
> or
>
> RefPtr<Foo> foo = rawPointerToFoo;
> foo->f()
>
> in its call site.
>
> The first approach guarantees that any call to f() is safe while the
> second approach is future proof if we add more code to use foo after
> calling f().
>
> I think it's good to agree on one convention here since managing
> lifetime of objects is tricky, and having one convention will make it
> easier to reason about things.
To preserve the encapsulation, it seems to me
RefPtr<Foo> protect(this);
makes more sense. If a method calls something that would cause the
object to be removed, the method itself should ensure the validity of
the following instructions.
The user of the interface should not have to know such implementation
detail of the object.
The second one is useful for other use cases:
RefPtr<Foo> foo = rawPointerToFoo;
doSomething(foo); // This could potentially destroy foo.
foo->f();
Benjamin
More information about the webkit-dev
mailing list