[webkit-dev] Stop Using Raw Pointers & References in New Code
rniwa at apple.com
Wed Jan 11 21:21:26 PST 2023
Alex recently added ThreadSafeWeakPtr <https://github.com/WebKit/WebKit/blob/main/Source/WTF/wtf/ThreadSafeWeakPtr.h>. That should address the last remaining use case of raw pointers (T*) and references (T&).
I suggest we stop using raw pointers and references in any local or heap stored variable. Only cases where raw pointers and references are permitted are function arguments — assuming every local variable / variable in stack is stored in a smart pointer, function arguments are safe to be raw pointers / references via transitive property. See Dangerous Use of Smart Pointers <https://lists.webkit.org/pipermail/webkit-dev/2020-September/031386.html> for a reference.
So, to recap, if we wanted shared ownership, or multiple pieces of code have to keep an object alive, use Ref <https://github.com/WebKit/WebKit/blob/main/Source/WTF/wtf/Ref.h> / RefPtr <https://github.com/WebKit/WebKit/blob/main/Source/WTF/wtf/RefPtr.h> with RefCounted <https://github.com/WebKit/WebKit/blob/main/Source/WTF/wtf/RefCounted.h> or ThreadSafeRefCounted <https://github.com/WebKit/WebKit/blob/main/Source/WTF/wtf/ThreadSafeRefCounted.h> whichever is appropriate. To store a weak reference to an object, use WeakPtr <https://github.com/WebKit/WebKit/blob/main/Source/WTF/wtf/WeakPtr.h> or ThreadSafeWeakPtr <https://github.com/WebKit/WebKit/blob/main/Source/WTF/wtf/ThreadSafeWeakPtr.h>, whichever is appropriate. When weak semantics is not needed (i.e. we don’t need to clear the pointer when the object goes away) for an external reference, use CheckedRef <https://github.com/WebKit/WebKit/blob/main/Source/WTF/wtf/CheckedRef.h> / CheckedPtr <https://github.com/WebKit/WebKit/blob/main/Source/WTF/wtf/CheckedPtr.h> so that we can release-assert when an object is about to get destroyed with outstanding external references.
I suppose we can consider exceptions to JSCell and other objects managed by GC but that should be more of an exception than norm. We should stop writing unsafe code going forward.
- R. Niwa
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the webkit-dev