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

Michael Catanzaro mcatanzaro at redhat.com
Tue Jan 24 12:53:42 PST 2023


On Tue, Jan 24 2023 at 11:33:45 AM -0800, Ryosuke Niwa via webkit-dev 
<webkit-dev at lists.webkit.org> wrote:
> That’s also the semantics of Ref/RefPtr in WebKit. But we’re 
> expanding the use of Ref/RefPtr to be beyond just owners for memory 
> safety. I don’t see how the situation is any different with 
> GRefPtr/GUniquePtr. If an explicit ownership isn’t appropriate, 
> then CheckedPtr/CheckedRef should be used instead.

The difference is we can modify WebKit C++ types to inherit from 
CanMakeCheckedPtr or CanMakeThreadSafeCheckedPtr, but we cannot modify 
types we don't control or types that are not even written in C++, so 
the smart pointer would have to do all the work of tracking ownership 
itself. std::shared_ptr and std::weak_ptr can do this for types that 
don't implement their own refcounting already. For types that *do* have 
their own refcounting, then I guess it's only doable if the type 
supports weak pointers. E.g. for GObjects, we could write GWeakPtr, but 
this would not be very ergonomic, and it won't work for arbitrary types.

Thinking about this more, I'm not sure this plan works for WeakPtrs? 
Say we have:

WeakPtr<Foo> f = /* initialized somehow */;
if (Foo* f = f.get())
{
  // do something
}

Then we already broke the rule against using a raw pointer in a local 
variable. That's the only way to use a WeakPtr, so we kind of have to, 
but as long as you have it stored in a raw pointer, then we gain no 
additional safety from the WeakPtr. CheckedPtr would work better in 
local variables, but again that's not an option for types we don't 
control.

Michael




More information about the webkit-dev mailing list