1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 00:47:45 +00:00

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
parent 7c74d3a657
commit ca413a5b50

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*;