Visual Studio(我正在使用2010但我已尝试过其他版本)告诉我,我的类行执行IMPLEMENT_DYNCREATE宏时出现内存泄漏。
重现步骤。
创建一个基本的MFC对话框应用程序。 使用类向导添加从CWinThread派生的类:
部首:
class CMyThread : public CWinThread
{
DECLARE_DYNCREATE(CMyThread)
protected:
CMyThread(); // protected constructor used by dynamic creation
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
protected:
DECLARE_MESSAGE_MAP()
};
CPP:
#include "stdafx.h"
#include "TestProject.h"
#include "MyThread.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// CMyThread
IMPLEMENT_DYNCREATE(CMyThread, CWinThread)
CMyThread::CMyThread()
{
}
BOOL CMyThread::InitInstance()
{
// TODO: perform and per-thread initialization here
return TRUE;
}
int CMyThread::ExitInstance()
{
// TODO: perform any per-thread cleanup here
return CWinThread::ExitInstance();
}
BEGIN_MESSAGE_MAP(CMyThread, CWinThread)
END_MESSAGE_MAP()
// CMyThread message handlers
现在,在标题中添加一个抽象的CWinThread Derived类:
class CThreadAbstract : public CWinThread
{
public:
virtual BOOL InitInstance() = 0;
virtual int ExitInstance() = 0;
};
并将您原来的CWinThread派生类更改为从CThreadAbstract派生而来:
class CMyThread : public CThreadAbstract
{
DECLARE_DYNCREATE(CMyThread)
protected:
CMyThread(); // protected constructor used by dynamic creation
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
protected:
DECLARE_MESSAGE_MAP()
};
现在,从对话框类(OnInitDialog)中实例化一个线程实例并将其关闭:
CMyThread * pMyThread = (CMyThread *)AfxBeginThread(RUNTIME_CLASS(CMyThread),0,0,CREATE_SUSPENDED);
if (pMyThread)
{
pMyThread->m_bAutoDelete = false;
pMyThread->ResumeThread();
}
if (pMyThread)
{
pMyThread->PostThreadMessage(WM_QUIT, 0, 0);
pMyThread = NULL;
}
在调试器中运行应用程序,然后单击“确定”按钮(或点击“esc”)将其关闭。
Whalla!内存泄漏指向:
IMPLEMENT_DYNCREATE(CMyThread, CWinThread)
显然,我并不确定这里发生的IMPLEMENT_DYNCREATE到底发生了什么。我已经阅读了MSDN文档,看到它说宏将实例化类的实例,所以我猜这是没有正确清理的,但我不知道如何修复它。 / p>
答案 0 :(得分:1)
当您设置m_bAutoDelete false时,您将负责删除CMyThread对象。