mirror of
https://github.com/RGBCube/serenity
synced 2025-07-26 09:07:35 +00:00
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:
parent
b0fef03e3f
commit
d07309a180
2 changed files with 20 additions and 0 deletions
|
@ -475,7 +475,16 @@ inline void swap(RefPtr<T, PtrTraitsT>& a, RefPtr<U, PtrTraitsU>& b)
|
||||||
a.swap(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::RefPtr;
|
||||||
using AK::static_ptr_cast;
|
using AK::static_ptr_cast;
|
||||||
|
|
|
@ -147,3 +147,14 @@ TEST_CASE(self_observers)
|
||||||
object->unref();
|
object->unref();
|
||||||
EXPECT_EQ(SelfAwareObject::num_destroyed, 1u);
|
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);
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue