浏览代码

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.
Brian Gianforcaro 4 年之前
父节点
当前提交
b0fef03e3f
共有 1 个文件被更改,包括 9 次插入0 次删除
  1. 9 0
      AK/OwnPtr.h

+ 9 - 0
AK/OwnPtr.h

@@ -191,6 +191,14 @@ inline void swap(OwnPtr<T>& a, OwnPtr<U>& b)
     a.swap(b);
 }
 
+template<typename T>
+inline OwnPtr<T> adopt_own_if_nonnull(T* object)
+{
+    if (object)
+        return OwnPtr<T>(object);
+    return {};
+}
+
 template<typename T>
 struct Traits<OwnPtr<T>> : public GenericTraits<OwnPtr<T>> {
     using PeekType = T*;
@@ -201,4 +209,5 @@ struct Traits<OwnPtr<T>> : public GenericTraits<OwnPtr<T>> {
 
 }
 
+using AK::adopt_own_if_nonnull;
 using AK::OwnPtr;