C++ shared_ptr自定義刪除器類

1、智能指針刪除器類

因爲用自己實現的內存池在釋放內存時需要buffer的大小纔可以,用函數和labda表達式不知道如何實現,所以用刪除器類實現自定義的智能指針刪除器。

/* 智能指針刪除器類 */
class CustomerDeleter
{
public:    
      CustomerDeleter(shared_ptr<RingMempool> MemPool, size_t buf_size):m_MemPool(MemPool),  m_BufSize(buf_size)    {            }    

    void operator()(char* buf)   
    {        
       printf("Free mempool[%p] buffer success \n", m_MemPool.get());       
       m_MemPool->Free(buf, m_BufSize);   
    }    
    
private:   
    shared_ptr<RingMempool> m_MemPool;    
    size_t m_BufSize;
};

class tmp1
{
public:    
    tmp1() {}   
    ~tmp1() {}   
    void Push(shared_ptr<char> buf) { Qbuf.push(buf); }   
    shared_ptr<char> pop() { shared_ptr<char> buf = Qbuf.front(); Qbuf.pop(); return buf; }   
    queue<shared_ptr<char> > Qbuf;
};
    
class CDeleter
{
public:    
      CDeleter(int buf_size, int num):m_buf_size(buf_size), m_num(num)   
      {     printf("111 buf_size[%d] num[%d]\n", buf_size, num);    }   
 
      void operator()(char* X)   
      {        printf("222 [%p] buf_size[%d] num[%d]\n", X, m_buf_size, m_num);        delete[] X;    }
   
private:   
      int m_buf_size = 0;    
      int m_num = 0;
 };
    
int main()
{
#if 0    
   char *tmpBuf =  (char *)m_VideoMemPool->Calloc(m_UsedVideoFrameBufSize);    
    if(tmpBuf == NULL)   
     {     
         printf("11m_mem_pool[%p]->Calloc Fail size[%d] for video channel \n", m_VideoMemPool.get(), m_UsedVideoFrameBufSize);        
         return -1;    
     }         
              
     /* 傳入使用的內存池及申請的內存塊的大小,自己實現的內存池銷燬時需要用到 */       
     std::shared_ptr<char> ds((char*)tmpBuf, CustomerDeleter(m_VideoMemPool, m_UsedVideoFrameBufSize));
 #endif   
      
     {           
       shared_ptr<char>buf1 = shared_ptr<char>(new char[100], CDeleter(100, 1));               
       shared_ptr<char>buf2 = shared_ptr<char>(new char[80], CDeleter(80, 2));            
       shared_ptr<char>buf3 = shared_ptr<char>(new char[80], CDeleter(80, 3));            
       T1.Push(buf1);            
       T1.Push(buf2);            
       T1.Push(buf3);    
     }        
     
      T1.pop();        
      T1.pop();        
      T1.pop();   
      return 0;
}

輸出
在這裏插入圖片描述

2、參考:

C++ 智能指針shared_ptr/unique_ptr自定義刪除器

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章