new and delete problem

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I creat a view in MyDlg using
m_pview=new MyView();

I am not sure where I should delete m_pview.

I called destroywindow in MyView and MyDlg, I have tried to delete m_pview
in destructor of MyView or MyDlg or PostNcDestroy() function , but all failed
because "Access violation" at line "delete m_pview".
If I don't delete m_pview, there is "memory leak" at line "m_pview=new
MyView()".

I have no idea about that. Any help or suggestion is appreciated!
 
Berrywong said:
I creat a view in MyDlg using
m_pview=new MyView();

I am not sure where I should delete m_pview.

I called destroywindow in MyView and MyDlg, I have tried to delete m_pview
in destructor of MyView or MyDlg or PostNcDestroy() function , but all failed
because "Access violation" at line "delete m_pview".
If I don't delete m_pview, there is "memory leak" at line "m_pview=new
MyView()".

Probably you deleted it twice. It should only be deleted once, and from
the same class where it is created. If you create it from MyDlg, delete
it from MyDlg. You should try to set it to 0 after deleting it, to
prevent accidental double deletions:

delete m_pview; m_pview = 0;

Even better, use std::auto_ptr or boost::scoped_ptr instead of native
pointers. They're way much safer:

#include "MyView.h"
class MyDlg
{
private:
std::auto_ptr<MyView> view;
};

then instead of
m_pview = new MyView;

do

view.reset(new MyView);

and never worry about deletion.

Tom
 
Back
Top