AK: Make RetainPtr and Retained more friendly towards const pointers.

Also add operator T&'s to Retained since it's nice to be able to pass them
to a function that takes a T&.
This commit is contained in:
Andreas Kling 2019-06-15 18:45:44 +02:00
parent 694b4a64bd
commit 01d1aee922
Notes: sideshowbarker 2024-07-19 13:35:56 +09:00
2 changed files with 41 additions and 13 deletions

View file

@ -103,20 +103,41 @@ public:
return *this;
}
RetainPtr& operator=(T* ptr)
template<typename U>
RetainPtr& operator=(const Retained<U>& other)
{
if (m_ptr != ptr)
if (m_ptr != other.ptr())
release_if_not_null(m_ptr);
m_ptr = ptr;
m_ptr = const_cast<T*>(other.ptr());
ASSERT(m_ptr);
retain_if_not_null(m_ptr);
return *this;
}
RetainPtr& operator=(T& object)
template<typename U>
RetainPtr& operator=(const RetainPtr<U>& other)
{
if (m_ptr != other.ptr())
release_if_not_null(m_ptr);
m_ptr = const_cast<T*>(other.ptr());
retain_if_not_null(m_ptr);
return *this;
}
RetainPtr& operator=(const T* ptr)
{
if (m_ptr != ptr)
release_if_not_null(m_ptr);
m_ptr = const_cast<T*>(ptr);
retain_if_not_null(m_ptr);
return *this;
}
RetainPtr& operator=(const T& object)
{
if (m_ptr != &object)
release_if_not_null(m_ptr);
m_ptr = &object;
m_ptr = const_cast<T*>(&object);
retain_if_not_null(m_ptr);
return *this;
}

View file

@ -44,16 +44,10 @@ public:
{
m_ptr->retain();
}
RETURN_TYPESTATE(unconsumed)
Retained(T& object)
: m_ptr(&object)
{
m_ptr->retain();
}
template<typename U>
RETURN_TYPESTATE(unconsumed)
Retained(U& object)
: m_ptr(&static_cast<T&>(object))
Retained(const U& object)
: m_ptr(&const_cast<T&>(static_cast<const T&>(object)))
{
m_ptr->retain();
}
@ -200,6 +194,19 @@ public:
return m_ptr;
}
CALLABLE_WHEN(unconsumed)
operator T&()
{
ASSERT(m_ptr);
return *m_ptr;
}
CALLABLE_WHEN(unconsumed)
operator const T&() const
{
ASSERT(m_ptr);
return *m_ptr;
}
private:
Retained() {}