声明一个结构体,具有构造以及析构函数:
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,个人感觉是一个不错的方式,能够提高代码质量;希望后面能够继续改进,加油啦,打工人希望自己越来越强