mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-21 23:20:20 +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
Notes:
sideshowbarker
2024-07-18 18:15:59 +09:00
Author: https://github.com/bgianfo Commit: https://github.com/SerenityOS/serenity/commit/d07309a1803 Pull-request: https://github.com/SerenityOS/serenity/pull/7026
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);
|
||||
}
|
||||
|
||||
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;
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue