当前位置: 代码迷 >> 综合 >> 共享指针
  详细解决方案

共享指针

热度:30   发布时间:2024-01-26 13:22:46.0

上次还在为图片数据的维护发愁,std::string肯定是不能再用了,那我们只能自己想办法了。第一个想到的当然是智能指针,shared_ptr,使用起来很简单代码改起来速度快。但是我们工程是VS2008写的不支持c++11,也没有引入boost库,所以这个方法暂时放一边。第二个就是不去维护,只引用这段内存的地址,程序启动时开辟内存,程序退出时释放内存。这个方法想想也不是不可以,但是不到万不得已不会用,因为造成资源的浪费。那么我就在想是不是可以模拟共享指针,维护一个引用计数,每次拷贝就对引用计数+1,每减少一次引用计数就-1,直到减少为0释放内存。下面把代码贴出来


class LayerImageBuffer
{
public:
LayerImageBuffer()
:m_use(NULL),m_data(NULL),m_len(0)
{

}

LayerImageBuffer(LPBYTE srcdata, DWORD len)
{
this->m_use = NULL;
if(srcdata)
{
this->m_use = new int(0);
++*(this->m_use);
}
this->m_data = srcdata;
this->m_len = len;
}

LayerImageBuffer(const LayerImageBuffer& thr)
{
this->m_data = thr.m_data;
this->m_len = thr.m_len;
this->m_use = thr.m_use;
if(this->m_use)
{
++*(this->m_use);
}
}

~LayerImageBuffer()
{
if(m_use)
{
if(0 == --*m_use)
{
delete m_use;
if(m_data)
delete m_data;
}
}
}

const LPBYTE data()
{
return m_data;
}

DWORD size()
{
return m_len;
}

int use()
{
return *m_use;
}

const LayerImageBuffer& operator = (const LayerImageBuffer& thr)
{
if(this->m_data == thr.m_data)//已经是相同的引用
return *this;

if(this->m_use && --*(this->m_use) == 0)
{
delete this->m_data;
delete this->m_use;
}

this->m_data = thr.m_data;
this->m_len = thr.m_len;
this->m_use = thr.m_use;
if(this->m_use)
++*(this->m_use);
return *this;
}

void set(const LPBYTE srcdata, int len)
{
if(this->m_data != srcdata)
{
//赋值前处理引用
if(this->m_use)
{
if(--*(this->m_use) == 0)
{
delete this->m_data;
delete this->m_use;

}
}
this->m_use = NULL;

if(srcdata)
{
this->m_use = new int(0);
++*(this->m_use);
}
this->m_data = srcdata;
this->m_len = len;
}
}

private:
LPBYTE m_data;
DWORD m_len;
int* m_use;
};

 

代码很简单,实际上也要的就是简单,经过测试完美解决了图片数据维护的问题。而且自己对共享指针这块也有一定了解了。

  相关解决方案