延迟销毁资源,不具备写时复制功能,贴出代码
class DataSource
{
private:
volatile unsigned int *m_pICount;
double *m_pData;
public:
DataSource(double *pData);
~DataSource();
DataSource(const DataSource &ds);
DataSource& operator =(const DataSource &ds);
bool operator ==(const DataSource &ds) const;
bool operator !=(const DataSource &ds) const;
private:
void release();
};
DataSource::DataSource(double *pData): m_pICount(new unsigned int(1)), m_pData(pData)
{
}
DataSource::~DataSource()
{
release();
}
DataSource::DataSource(const DataSource &ds): m_pICount(ds.m_pICount), m_pData(ds.m_pData)
{
if(*this == ds)
return;
++(*m_pICount);
}
DataSource& DataSource::operator =(const DataSource &ds)
{
if(*this == ds)
return *this;
this->release();
m_pData = ds.m_pData;
m_pICount = ds.m_pICount;
++(*m_pICount);
return *this;
}
bool DataSource::operator ==(const DataSource &ds) const
{
return (m_pICount == ds.m_pICount && m_pData == ds.m_pData);
}
bool DataSource::operator !=(const DataSource &ds) const
{
return (m_pICount != ds.m_pICount);
}
void DataSource::release()
{
if(0 == --(*m_pICount))
{
delete m_pICount;
delete m_pData;
m_pICount = NULL;
m_pData = NULL;
}
}