我的代码简写如下:
class CLogMngr
{
public:
CLogMngr();
virtual ~CLogMngr();
public:
void Setup(_ConnectionPtr cnnt, CString& user,long & Authority)
{
m_DBCnt = cnnt;
m_user = user;
m_Authority=Authority;
}
protected:
_ConnectionPtr m_DBCnt;
CString m_user;
long m_Authority;
};
CLogMngr::CLogMngr()
{
}CLogMngr::~CLogMngr()
{
}
class CSCHOOlApp : public CWinApp
{
public:
_ConnectionPtr m_DBCnt;
CLogMngr m_logMngr;
}
BOOL CSCHOOlApp::InitInstance()
{
try
{
m_DBCnt.CreateInstance(_uuidof(Connection));
CString sql_;
_RecordsetPtr pRst=NULL;
sql_.Format("DSN=SCHOOL;UID=anxing;PWD=234811");
_bstr_t sql=sql_;
VARIANT holder;
m_DBCnt->Open(sql,"","",-1);
sql_.Format("select * from table ");
sql=sql_;
pRst=m_DBCnt->Execute(sql,NULL,adCmdText);
pRst->Close();
}
catch(_com_error &e)
{
AfxMessageBox(e.ErrorMessage());
}
return TRUE;
};
int CSCHOOlApp::ExitInstance()
{
m_DBCnt->Close();
return CWinApp::ExitInstance();
}
在VIEW中我通过全局对象theApp来得到m_DBCnt
class CMYView : public CFormView
{
protected:
_ConnectionPtr m_DBCnt;
CLogMngr *m_logMngr;}
extern CSCHOOlApp theApp;
CMYView::CMYView()
{
m_DBCnt=theApp.m_DBCnt;
m_logMngr=&(theApp.m_logMngr);
}
如果应用程序打开后关闭(什么也不做)一切正常。但是当我对于VIEWF进行操作。如在VIEW中对数据库进行添加。结束时出现了引用非法内存。f5调试出现对话框Unhanded exception in anxing.exe
是在应用程序结束析构
CLogMngr::~CLogMngr(){}默认调用Release()时出现了错误。
请问:在哪里可能出现了错误?
m_DBCnt=theApp.m_DBCnt;
m_logMngr=&(theApp.m_logMngr);
估计你把把m_DBCnt,m_logMngr放到theApp里了。因为它们被放到全局变量里,则在它们析构的时候,有可能Com环境已经关闭了。即,程序在调用CoUnitianlize(或者类似的函数)之后,再调用theApp的析构函数,而theApp的析构函数再调用 Connection的析构函数,则因为Com环境已经关闭,则出现Release异常。
知道原因,处理就容易了。
在CLogMngr中增加自己的析构过程处理,在COM环境关闭之前自己调用。
坛子里以前有一帖子讨论过类似问题。