参照カウントの単純な実装
1699 ワード
リソースの破棄を遅らせ、書き込み時のコピー機能を備えず、コードを貼り付ける
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;
}
}