[webkit-dev] Stop Using Raw Pointers & References in New Code

Ryosuke Niwa rniwa at apple.com
Thu Jan 12 18:59:23 PST 2023

> On Jan 12, 2023, at 6:50 PM, Michael Catanzaro <mcatanzaro at redhat.com> wrote:
> On Thu, Jan 12 2023 at 12:35:09 PM -0800, Ryosuke Niwa via webkit-dev <webkit-dev at lists.webkit.org> wrote:
>> So… instead of:
>> foo(bar());
>> do:
>> foo(RefPtr { bar() }.get());
> What's the value of creating a temporary RefPtr just to get at the underlying raw pointer? Isn't this overkill?

The benefit is that bar() will be kept alive while the duration of call to foo. Without, whatever bar() returns can be dead before foo() finishes running, which can result in use-after-free.

An obvious alternative is to use smart pointer types on each function argument. But this has a few drawbacks:
The same rule can’t be applied to “this” since passing of “this" pointer is implicit in C++.
Ref churn when multiple functions are called with the same object; e.g.
foo = foo()
bar(foo); // ref/deref here
baz(foo); // ref/deref here again
Ref churn when a function argument is passed to another function; e.g.
void foo(RefPtr<T>&& obj)
    bar(obj); // ref/deref here even though obj is guaranteed to be alive throughout this function

- R. Niwa

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.webkit.org/pipermail/webkit-dev/attachments/20230112/8c0421a4/attachment.htm>

More information about the webkit-dev mailing list