[webkit-dev] Set once pointer types and static analysis
Chris Dumez
cdumez at apple.com
Mon Oct 28 14:59:59 PDT 2024
I’m not sure it is worth the extra complexity personally.
> On Oct 28, 2024, at 11:48 AM, Ryosuke Niwa via webkit-dev <webkit-dev at lists.webkit.org> wrote:
>
> Hi all,
>
> In WebKit, it’s fairly common to write a member variable as RefPtr or std::unique_ptr that later gets lazily initialized to some value but never unset or assigned of a different value after that.
>
> e.g.
>
> class Foo {
> Bar& bar() {
> if (!m_bar)
> m_bar = Bar::create();
> return *m_bar;
> }
> Ref<Bar> protectedBar() { return bar(); }
>
> RefPtr<Bar> m_bar;
> }
>
> Assuming there is no other code modifying m_bar, foo->bar()->method() is always safe to call even if method wasn’t a trivial function. Right now, static analyzer doesn’t recognize this pattern so we’d be forced to write code like this: foo->protectedBar()->method() where ensureProtectedBar is a wrapper around ensureBar which returns Ref<Bar>.
>
> A suggestion was made that static analyzer can recognize this patten. Specifically, if we introduced a new smart pointer types that only allow setting the value once, static analyzer can allow foo->bar()->method()and avoid ref-churn in some cases:
>
> e.g.
>
> class Foo {
> Bar& bar() {
> if (!m_bar)
> m_bar = Bar::create();
> return *m_bar;
> }
>
> SetOnceRefPtr<Bar> m_bar;
> }
>
> SetOnceRefPtr::operator=(T*) release asserts that m_ptr isn’t set, and doesn’t have a move constructor, operator=(nullptr_t), leakRef(), releaseNonNull(), etc… which can override the value of m_ptr after setting the value via operator= or in constructor.
>
> We could create various variants: SetOnceRef, SetOnceUniquePtr, SetOnceUniqueRef.
>
> Do you think this will be useful?
>
> - R. Niwa
>
> _______________________________________________
> webkit-dev mailing list
> webkit-dev at lists.webkit.org
> https://lists.webkit.org/mailman/listinfo/webkit-dev
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.webkit.org/pipermail/webkit-dev/attachments/20241028/4e73a794/attachment.htm>
More information about the webkit-dev
mailing list