AK: Use swap-based assignment in OwnPtr

Also provide a specialized swap(OwnPtr, OwnPtr) that allows swapping
an OwnPtr with itself.
This commit is contained in:
Andreas Kling 2020-01-24 09:31:14 +01:00
commit ca413a5b50
Notes: sideshowbarker 2024-07-19 09:51:38 +09:00

View file

@ -91,29 +91,25 @@ public:
OwnPtr& operator=(OwnPtr&& other) OwnPtr& operator=(OwnPtr&& other)
{ {
if (this != &other) { OwnPtr ptr(move(other));
delete m_ptr; swap(ptr);
m_ptr = other.leak_ptr();
}
return *this; return *this;
} }
template<typename U> template<typename U>
OwnPtr& operator=(OwnPtr<U>&& other) OwnPtr& operator=(OwnPtr<U>&& other)
{ {
if (this != static_cast<void*>(&other)) { OwnPtr ptr(move(other));
delete m_ptr; swap(ptr);
m_ptr = other.leak_ptr();
}
return *this; return *this;
} }
template<typename U> template<typename U>
OwnPtr& operator=(NonnullOwnPtr<U>&& other) OwnPtr& operator=(NonnullOwnPtr<U>&& other)
{ {
ASSERT(m_ptr != other.ptr()); OwnPtr ptr(move(other));
delete m_ptr; swap(ptr);
m_ptr = other.leak_ptr(); ASSERT(m_ptr);
return *this; return *this;
} }
@ -184,10 +180,27 @@ public:
operator bool() { return !!m_ptr; } 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: private:
T* m_ptr = nullptr; T* m_ptr = nullptr;
}; };
template<typename T, typename U>
inline void swap(OwnPtr<T>& a, OwnPtr<U>& b)
{
a.swap(b);
}
template<typename T> template<typename T>
struct Traits<OwnPtr<T>> : public GenericTraits<OwnPtr<T>> { struct Traits<OwnPtr<T>> : public GenericTraits<OwnPtr<T>> {
using PeekType = const T*; using PeekType = const T*;