关于智能指针的问题,求助高手
因为项目的需要,我自定义了一个简化的指针类方便在程序结束时候清理原始指针所指向的数据.但是程序在析构函数的时候报错(User breakpoint called from code at 0xxxxxxxxx),代码如下:
template <class T>
class IVPoint
{
private:
T* m_pIVPoint;
public:
IVPoint()
{
m_pIVPoint = NULL;
}
IVPoint(T* pIV){ m_pIVPoint = pIV; }
~IVPoint()
{
if (m_pIVPoint)
{
imaqDispose(m_pIVPoint);
}
}
T* GetInst()const{ return m_pIVPoint; }
T* operator-> (){ return m_pIVPoint; }
T& operator*(){ return *m_pIVPoint; }
T* operator=(T* pIV)
{
if (m_pIVPoint && (m_pIVPoint != pIV))
{
imaqDispose(m_pIVPoint);
}
return (m_pIVPoint = pIV);
}
IVPoint <T> & operator=(const IVPoint <T> & IV )
{
if (IV.m_pIVPoint != m_pIVPoint)
{
imaqDispose(m_pIVPoint);
m_pIVPoint = IV.m_pIVPoint;
}
return *this;
}
int operator==(T* pIV)const{ return (m_pIVPoint == pIV); }
int operator!=(T* pIV)const{ return (m_pIVPoint != pIV); }
};
请高手指教到底错在哪里?
注: imaqDispose()是一个清理指针所指向数据的函数,在别处使用的时候没有问题. 谢谢各位啦!
[解决办法]
您还是找本C++ Primer,温习一下运算符重载吧。
bool operator==(const T & pIV)const;
bool operator!=(const T & pIV)const;
------解决方案--------------------
你的问题是当拷贝构造和赋值这两个操作被执行的时候,没有将被拷贝(或赋值方)的那个智能指针对象的内部指针置空,导致最后析构的时候对一块内存释放了两次,产生错误.
另外你的operator=的返回类型不正确,应该返回类类型才对,而另外要重载一个operator*来获得内部指针的指向内容
我在下面把你的copy ctor,operator*和operator=写一下: