From b0fef03e3f24a1c9ca3028f313a23bb1988081b6 Mon Sep 17 00:00:00 2001 From: Brian Gianforcaro Date: Wed, 12 May 2021 20:35:08 -0700 Subject: [PATCH] AK: Introduce adopt_own_if_nonnull(..) to aid in Kernel OOM hardening Unfortunately adopt_own requires a reference, which obviously does not work well with when attempting to harden against allocation failure. The adopt_own_if_nonnull() variant will allow you to avoid using bare pointers, while still allowing you to handle allocation failure. --- AK/OwnPtr.h | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/AK/OwnPtr.h b/AK/OwnPtr.h index 416af312e2..e6d62c6507 100644 --- a/AK/OwnPtr.h +++ b/AK/OwnPtr.h @@ -191,6 +191,14 @@ inline void swap(OwnPtr& a, OwnPtr& b) a.swap(b); } +template +inline OwnPtr adopt_own_if_nonnull(T* object) +{ + if (object) + return OwnPtr(object); + return {}; +} + template struct Traits> : public GenericTraits> { using PeekType = T*; @@ -201,4 +209,5 @@ struct Traits> : public GenericTraits> { } +using AK::adopt_own_if_nonnull; using AK::OwnPtr;