聲明一個結構體,具有構造以及析構函數:
typedef struct _File
{
unsigned char *pData;
int size;
_File(int size)
{
std::cout<<"1111111111"<<endl;
pData = new unsigned char[size];
memset(pData,0,size);
}
~_File()
{
std::cout<<"2222222222"<<endl;
if (pData)
{
delete[] pData;
pData = NULL;
}
}
};
在main函數中這樣用,使用boost智能指針,自動釋放的同時,調用我們的析構函數,實作我們的手動delete
boost::lockfree::queue<struct _File*,boost::lockfree::capacity<1024>> m_queues;
for (int i =0; i < 300; i ++)
{
boost::shared_ptr<struct _File> m_p(new struct _File(11));
m_queues.push(m_p.get());
}
int a = 65535;
while(a > 0)
{
//boost::shared_ptr<struct _File> m_p(new struct _File);
struct _File*p = NULL;
m_queues.pop(p);
if (p == NULL)
{
while(1);
}else
{
std::cout<<"3333333"<<std::endl;
std::cout<<"pop"<<sizeof(struct _File)<<std::endl;
}
}

總結:這樣能夠避免忘記delete,個人感覺是一個不錯的方式,能夠提高代碼品質;希望後面能夠繼續改進,加油啦,打勞工希望自己越來越強