Search code examples
c++wxwidgets

Reference counting in wxWidgets, how does it work in this simple case?


My program is crashing and I'm having a hard time wrapping my head around why it crashes. The main problem is that the wxwidgets documentation says that reference counting is used for wxImage objects. What exactly does this mean? Why does this code crash it?

wxImage* t = m_default_image; //m_default_image is a pointer pointing to a valid wxImage object.

wxDELETE(m_default_image);
if(t->IsOk())
{
    wxLogMessage("reference counting works!");
}

The line that crashes is the t->IsOK(). Shouldn't the reference counting prevent the actual object from being deleted so my t ptr still points to something valid?


Solution

  • Let me explain what is happening:

    1. You create a pointer to a wxImage that you have already created somewhere.
    2. You then delete it.
    3. You then attempt to dereference a deleted pointer and call 'IsOk()' on the resulting object, which doesn't exist anymore, because of the previous step.

    Step 2 may or may not have actually deleted the object, but it likely deleted the reference as well. Depending on how wx implemented reference counting, and how you've managed references, the wxImage object may have a reference count of one at the start of your routine - therefore, wxDELETE will reduce the reference count to zero, and thus delete the object as well.

    There is no way that wx could automatically manage your objects using reference counts if you are using pointers in the way you are. Perhaps you want to use the copy constructor, and stop using manual memory handling? C++ has the RAII technique - use it.

    Lastly, can I ask why m_default_image is a pointer? You're just making life hard for yourself by using raw pointers all the time.