delete 总出异常

来源:互联网 发布:楚楚街和淘宝哪个靠谱 编辑:程序博客网 时间:2024/06/10 10:40

相关 url http://community.csdn.net/Expert/topic/3160/3160520.xml?temp=.199032

测试工程说明

class CNewFree :
 public INewFree,
 public CComObjectRoot,
 public CComCoClass
{
public:
 CNewFree() {}
BEGIN_COM_MAP(CNewFree)
 COM_INTERFACE_ENTRY(INewFree)
END_COM_MAP()
DECLARE_NOT_AGGREGATABLE(CNewFree)

DECLARE_REGISTRY_RESOURCEID(IDR_NewFree)

// INewFree
public:
 STDMETHOD(GetMem)(/*[in]*/BYTE** pbMem);
};
-------------------------------
#include
#include

STDMETHODIMP CNewFree::GetMem(BYTE **pbMem)
{
 CString *pstr = new CString("1111111111111");
 
 *pbMem = (BYTE*)pstr;

 return S_OK;
}
===============================
测试端代码
LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
 {
  INewFree *pINewFree = NULL;
  CoCreateInstance(__uuidof(NewFree), NULL, CLSCTX_INPROC_SERVER,
   __uuidof(INewFree), (void**)&pINewFree);

  
  BYTE* pbData = NULL;
  pINewFree->GetMem(&pbData);
  CString * pstr = NULL;
  pstr = (CString*)pbData;

  delete pstr; // 一运行这里就出错!!! why???
 
  return 0;
 }

-----------------------------------------------------------------------

错误分析,因为 wtl 的CString 的析够函数不是 virtual 的,所以delete 的时候, heap 无效

-----------------------------------------------------------------------------

解决方案:

class CMyString

{

public:

        CMyString()

       {

                  m_str = "";

      }

virtual ~CMyString()

       {

}

 

CString m_str;

}

 

原创粉丝点击