From c5430cbbcd3ed8ed2d7036fcb67376355a695247 Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Thu, 23 Sep 2021 22:43:31 +0100 Subject: [PATCH] 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. --- include/wx/object.h | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/include/wx/object.h b/include/wx/object.h index adc0c03ab1..e951b218d3 100644 --- a/include/wx/object.h +++ b/include/wx/object.h @@ -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 wxObjectDataPtr& operator=(const wxObjectDataPtr &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; }