summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibCore
diff options
context:
space:
mode:
authorAndreas Kling <kling@serenityos.org>2021-11-24 13:09:51 +0100
committerAndreas Kling <kling@serenityos.org>2021-11-24 13:52:01 +0100
commitb81ce827b655b0985b4230cba5c4df466658bcb2 (patch)
tree369cdb0627220c0ecc8b5fecbe154f5fe12f1345 /Userland/Libraries/LibCore
parent2efec90fb7287cf3c7836ed99e5db57157a06cc8 (diff)
downloadserenity-b81ce827b655b0985b4230cba5c4df466658bcb2.zip
LibCore: Add Core::Object::try_add<T>(...)
This is a fallible version of add<T>(...) that returns ErrorOr<T>. It can be used together with TRY() to handle allocation failures when instantiating new Core::Objects.
Diffstat (limited to 'Userland/Libraries/LibCore')
-rw-r--r--Userland/Libraries/LibCore/Object.cpp10
-rw-r--r--Userland/Libraries/LibCore/Object.h10
2 files changed, 18 insertions, 2 deletions
diff --git a/Userland/Libraries/LibCore/Object.cpp b/Userland/Libraries/LibCore/Object.cpp
index 50b4091f71..19dd4134b4 100644
--- a/Userland/Libraries/LibCore/Object.cpp
+++ b/Userland/Libraries/LibCore/Object.cpp
@@ -73,14 +73,20 @@ void Object::event(Core::Event& event)
}
}
-void Object::add_child(Object& object)
+ErrorOr<void> Object::try_add_child(Object& object)
{
// FIXME: Should we support reparenting objects?
VERIFY(!object.parent() || object.parent() == this);
+ TRY(m_children.try_append(object));
object.m_parent = this;
- m_children.append(object);
Core::ChildEvent child_event(Core::Event::ChildAdded, object);
event(child_event);
+ return {};
+}
+
+void Object::add_child(Object& object)
+{
+ MUST(try_add_child(object));
}
void Object::insert_child_before(Object& new_child, Object& before_child)
diff --git a/Userland/Libraries/LibCore/Object.h b/Userland/Libraries/LibCore/Object.h
index cb627ba9a3..8d468b54b0 100644
--- a/Userland/Libraries/LibCore/Object.h
+++ b/Userland/Libraries/LibCore/Object.h
@@ -129,6 +129,8 @@ public:
void stop_timer();
bool has_timer() const { return m_timer_id; }
+ ErrorOr<void> try_add_child(Object&);
+
void add_child(Object&);
void insert_child_before(Object& new_child, Object& before_child);
void remove_child(Object&);
@@ -164,6 +166,14 @@ public:
return child;
}
+ template<class T, class... Args>
+ inline ErrorOr<NonnullRefPtr<T>> try_add(Args&&... args)
+ {
+ auto child = TRY(T::try_create(forward<Args>(args)...));
+ TRY(try_add_child(*child));
+ return child;
+ }
+
virtual bool is_visible_for_timer_purposes() const;
bool is_being_inspected() const { return m_inspector_count; }