Fix self-assignment bug in wxObjectDataPtr

wxObjectDataPtr::operator=() didn't handle self-assignment correctly,
i.e. could delete the object when doing "x = x".

Fix this by incrementing the reference count before decrementing it on
possibly the same object to ensure that it never reaches 0.
This commit is contained in:
Vadim Zeitlin 2021-09-23 22:43:31 +01:00
parent 29c408c3c5
commit c5430cbbcd

View File

@ -331,22 +331,26 @@ public:
wxObjectDataPtr& operator=(const wxObjectDataPtr &tocopy)
{
// Take care to increment the reference first to ensure correct
// behaviour in case of self-assignment.
T* const ptr = tocopy.m_ptr;
if (ptr)
ptr->IncRef();
if (m_ptr)
m_ptr->DecRef();
m_ptr = tocopy.m_ptr;
if (m_ptr)
m_ptr->IncRef();
m_ptr = ptr;
return *this;
}
template <typename U>
wxObjectDataPtr& operator=(const wxObjectDataPtr<U> &tocopy)
{
T* const ptr = tocopy.get();
if (ptr)
ptr->IncRef();
if (m_ptr)
m_ptr->DecRef();
m_ptr = tocopy.get();
if (m_ptr)
m_ptr->IncRef();
m_ptr = ptr;
return *this;
}