AK: Introduce adopt_ref_if_nonnull(..) to aid in Kernel OOM hardening

Unfortunately adopt_ref requires a reference, which obviously does not
work well with when attempting to harden against allocation failure.
The adopt_ref_if_nonnull() variant will allow you to avoid using bare
pointers, while still allowing you to handle allocation failure.
This commit is contained in:
Brian Gianforcaro 2021-05-12 21:02:43 -07:00 committed by Andreas Kling
parent b0fef03e3f
commit d07309a180
2 changed files with 20 additions and 0 deletions

View file

@ -475,7 +475,16 @@ inline void swap(RefPtr<T, PtrTraitsT>& a, RefPtr<U, PtrTraitsU>& b)
a.swap(b);
}
template<typename T>
inline RefPtr<T> adopt_ref_if_nonnull(T* object)
{
if (object)
return RefPtr<T>(RefPtr<T>::Adopt, *object);
return {};
}
}
using AK::adopt_ref_if_nonnull;
using AK::RefPtr;
using AK::static_ptr_cast;

View file

@ -147,3 +147,14 @@ TEST_CASE(self_observers)
object->unref();
EXPECT_EQ(SelfAwareObject::num_destroyed, 1u);
}
TEST_CASE(adopt_ref_if_nonnull)
{
RefPtr<SelfAwareObject> object = adopt_ref_if_nonnull(new SelfAwareObject);
EXPECT_EQ(object.is_null(), false);
EXPECT_EQ(object->ref_count(), 1u);
SelfAwareObject* null_object = nullptr;
RefPtr<SelfAwareObject> failed_allocation = adopt_ref_if_nonnull(null_object);
EXPECT_EQ(failed_allocation.is_null(), true);
}