一, 问题场景
代码中使用自定义数据类型时,为了提高入参,出参普遍性。使用了void *指针类型管理入参出参。当释放内存时没有指定指针指向的类型,从而导致内存泄露。
typedef std::shared_ptr<SPIWorker> SPIWorker;
typedef std::weak_ptr<SPIWorker> WPIWorker;
typedef std::shared_prt<SPIObserver> SPIObserver;
typedef std::weak_ptr<SPIObserver> WPIObserver;
class CTaskOpr
{
public:
CTaskOpr():m_pInParam(NULL), m_pOutData(NULL){}
virtual ~CTaskOpr(){}
virtual void SetProxy(SPIWorker spWorker){ m_wpWorker = spWorker;}
virtual void SetObserver(SPIObserver spObserver){ m_wpObserver = spObserver;}
//直接使用父类时,不能重复调用此接口,需要对应子类知道参数类型,才能正确释放内存
virtual void SetInParam(const void *pInParam) = 0;
virtual int OnWork()
{
if(m_wpWorker.expired()) return -1;
SPIWorker spWorker = m_wpWorker.lock()
return spWorker->Work(m_pInParam, m_pOutData);
}
virtual int Notify()
{
if(m_wpObserver.expired()) return -1;
SPIObserver spObserver = m_wpObserver.lock();
return spObserver->Notify(m_pOutData);
}
protected:
void *m_pInParam;
void *m_pOutData;
WPIWorker m_wpWorker;
WPIObserver m_wpObserver;
}
typedef std::shared_ptr<CTaskOpr> SPTaskOpr;
使用该父类时,直接对void *指针delete操作导致,内存泄露:
typedef struct _SProduceParam
{
std::string metal;
int count;
}SProduceParam, *PSProduceParam;
class CProduceTask :public CTaskOpr
{
public:
virtual ~CProduceTask(){
if(m_pInParam)
{
delete (PSProduceParam)m_pInParam; //直接delete会导致内存泄露
m_pInParam = NULL;
}
}
void SetInParam(const void *pInParam)
{
if(m_pInParam)
{
delete (PSProduceParam)m_pInParam;
m_pInParam = NULL;
}
m_pInParam = new SProduceParam;
assert(m_pInParam);
(*m_pInParam) = *pInParam;
}
}