diff options
author | Andreas Kling <kling@serenityos.org> | 2020-01-24 09:31:14 +0100 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-01-24 09:35:55 +0100 |
commit | ca413a5b505ce41e5da8644dada24d59acfd411f (patch) | |
tree | dd9c011e3dce9d034697589c8bf7d5be6fa3a325 /AK | |
parent | 7c74d3a6576b892e4f1d9f1aa9305b01ad673cb4 (diff) | |
download | serenity-ca413a5b505ce41e5da8644dada24d59acfd411f.zip |
AK: Use swap-based assignment in OwnPtr
Also provide a specialized swap(OwnPtr, OwnPtr) that allows swapping
an OwnPtr with itself.
Diffstat (limited to 'AK')
-rw-r--r-- | AK/OwnPtr.h | 35 |
1 files 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<typename U> OwnPtr& operator=(OwnPtr<U>&& other) { - if (this != static_cast<void*>(&other)) { - delete m_ptr; - m_ptr = other.leak_ptr(); - } + OwnPtr ptr(move(other)); + swap(ptr); return *this; } template<typename U> OwnPtr& operator=(NonnullOwnPtr<U>&& 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<typename U> + void swap(OwnPtr<U>& other) + { + ::swap(m_ptr, other.m_ptr); + } + private: T* m_ptr = nullptr; }; +template<typename T, typename U> +inline void swap(OwnPtr<T>& a, OwnPtr<U>& b) +{ + a.swap(b); +} + template<typename T> struct Traits<OwnPtr<T>> : public GenericTraits<OwnPtr<T>> { using PeekType = const T*; |