tags:

views:

168

answers:

1

How can I destroy a pointer to CFindReplaceDialog object properly?

For example I have class:

class CjumpView : public CRichEditView
{
   CFindReplceDialog *m_pFRDlg;
  // ...


   }; 
CjumpView::CjumpView()
: m_pFRDlg(NULL)
{

}

CjumpView::~CjumpView()
{
   if(m_pFRDlg != NULL)
   {
      m_pFRDlg->DestroyWindow();
      delete(m_pFRDlg);
   }
}

void CjumpView::OnEditFind()
{
    if(m_pFRDlg == NULL)
    {
     const bool fShowFind = true;
     m_pFRDlg = new CFindReplaceDialog();
     m_pFRDlg->Create(fShowFind, m_sFind, NULL, NULL, this)
    }

}



LRESULT CjumpView::OnFind(WPARAM, LPARAM lParam)
{
    LPFINDREPLACE lpFindReplace = reinterpret_cast<LPFINDREPLACE>(lParam);
    if(lpFindReplace->Flags & FR_DIALOGTERM)
    {
     m_pFRDlg->DestroyWindow();
            delete(m_pFRDlg);
            m_pFRDlg = NULL;
     return NULL;
    }
    lpFindReplace->Flags = 0;
    return NULL;
}

In Visual Studio CFindReplaceDialog help atricle it is said that objects of this class should be created in heap using "new" operator. Then Create member function should be called. My "OnFind" function reacts on closing of this Find dialog. It calls DestroyWindow() function, the tries to delete dialog object.

But when I try to call DestoyWindow() in OnFind() or in destructor I have an exception "Access violation at address...".

How to destroy this dialog and to delete pointer?

+1  A: 

If someone's interested as me on this problem, the solution is simple. Actually you don't have to delete CFindReplaceDislog* pointer after it has been used.

After it's closed, it receives WM_NCDESTROY message. And as far as it's derived from CWnd, CWnd::OnNcDestroy() handler is invoked. In the last line it calls PostNcDestroy() which does nothing in CWnd, but overriden in CFindReplaceDialog. There it deletes 'this' pointer like so:

void CFindReplaceDialog::PostNcDestroy()
{
    ASSERT(m_hWnd == NULL);
    delete this;
}

So, you don't have to invoke

delete(m_pFRDlg)

anywhere

Nikita Borodulin