From ca413a5b505ce41e5da8644dada24d59acfd411f Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Fri, 24 Jan 2020 09:31:14 +0100 Subject: [PATCH] AK: Use swap-based assignment in OwnPtr Also provide a specialized swap(OwnPtr, OwnPtr) that allows swapping an OwnPtr with itself. --- AK/OwnPtr.h | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/AK/OwnPtr.h b/AK/OwnPtr.h index 885d0974e2..162c756e17 100644 --- a/AK/OwnPtr.h +++ b/AK/OwnPtr.h @@ -91,29 +91,25 @@ public: OwnPtr& operator=(OwnPtr&& other) { - if (this != &other) { - delete m_ptr; - m_ptr = other.leak_ptr(); - } + OwnPtr ptr(move(other)); + swap(ptr); return *this; } template OwnPtr& operator=(OwnPtr&& other) { - if (this != static_cast(&other)) { - delete m_ptr; - m_ptr = other.leak_ptr(); - } + OwnPtr ptr(move(other)); + swap(ptr); return *this; } template OwnPtr& operator=(NonnullOwnPtr&& other) { - ASSERT(m_ptr != other.ptr()); - delete m_ptr; - m_ptr = other.leak_ptr(); + OwnPtr ptr(move(other)); + swap(ptr); + ASSERT(m_ptr); return *this; } @@ -184,10 +180,27 @@ public: operator bool() { return !!m_ptr; } + void swap(OwnPtr& other) + { + ::swap(m_ptr, other.m_ptr); + } + + template + void swap(OwnPtr& other) + { + ::swap(m_ptr, other.m_ptr); + } + private: T* m_ptr = nullptr; }; +template +inline void swap(OwnPtr& a, OwnPtr& b) +{ + a.swap(b); +} + template struct Traits> : public GenericTraits> { using PeekType = const T*;