C++智能指針shared_ptr分析。本站提示廣大學習愛好者:(C++智能指針shared_ptr分析)文章只能為提供參考,不一定能成為您想要的結果。以下是C++智能指針shared_ptr分析正文
C++智能指針shared_ptr分析
概要:
shared_ptr是c++智能指針中適用場景多,功能實現較多的智能指針。它采取引用計數的方法來實現釋放指針所指向的資源。下面是我代碼實現的基本功能。
實例代碼:
template<class T>
class sharedptr
{
public:
sharedptr(T* ptr)
:_ptr(ptr)
, _refCount(new int(1))
{}
sharedptr(sharedptr<T>& sp)
:_ptr(sp._ptr)
, _refCount(sp._refCount)
{
++(*_refCount);
}
sharedptr& operator = (sharedptr<T>& sp) //現代寫法
{
swap(_ptr, sp._ptr);
swap(_refCount, sp._refCount);
return *this;
}
/*sharedptr& operator = (sharedptr<T>& sp)
{
if (this != &sp)
{
this->Release();
_ptr = sp._ptr;
_refCount = sp._refCount;
++(*_refCount);
}
return *this;
}*/
void Release()
{
if (--(*_refCount) == 0)
{
delete _ptr;
delete _refCount;
}
}
~sharedptr()
{
Release();
}
private:
T* _ptr;
int* _refCount;
};
但是呢這只能刪除基本類型,例int、double類型指針。但對於數組指針不是適用。在c++中動態內存管理中,new/delete對應,new[]/delete[]對應,所以就引入了定制刪除器這個概念。
定制刪除器基本的實現就是:
template<class T>
struct Delete
{
void operator()(T* ptr)
{
delete ptr;
}
};
template<class T>
struct DeleteArray
{
void operator()(T* ptr)
{
delete[] ptr;
}
};
如何在shared_ptr中使用呢,下來我用代碼簡單做個示范。
template<class T> //定制刪除器
struct Delete
{
void operator()(T* ptr)
{
delete ptr;
}
};
template<class T>//定制刪除器
struct DeleteArray
{
void operator()(T* ptr)
{
delete[] ptr;
}
};
template<class T, class D = Delete<T>>
class sharedptr
{
public:
sharedptr(T* ptr, D del)
:_ptr(ptr)
, _refCount(new int(1))
, _del(del)
{}
sharedptr(sharedptr<T>& sp)
:_ptr(sp._ptr)
, _refCount(sp._refCount)
{
++(*_refCount);
}
sharedptr& operator = (sharedptr<T>& sp) //現代寫法
{
swap(_ptr, sp._ptr);
swap(_refCount, sp._refCount);
return *this;
}
/*sharedptr& operator = (sharedptr<T>& sp)
{
if (this != &sp)
{
this->Release();
_ptr = sp._ptr;
_refCount = sp._refCount;
++(*_refCount);
}
return *this;
}*/
void Release()
{
if (--(*_refCount) == 0)
{
printf("delete:0x%p\n", _ptr);
_del(_ptr);
delete _refCount;
}
}
~sharedptr()
{
Release();
}
private:
T* _ptr;
int* _refCount;
D _del;
};
在調用時,應這樣寫調用函數:
void TextSharedptr()
{
DeleteArray<int> da;
sharedptr<int, DeleteArray<int>> sp(new int[3], da);
}
而weak_ptr弱引用智能指針是通過(引用不增加計數)來打破循環引用的;
什麼循環引用,這可以簡單用一個雙向鏈表來解釋:
而weak_ptr通過只引用不增加計數的方法打破了循環引用這個問題。但在使用weak_ptr的前提是確定在使用shared_ptr智能指針時存在循環引用這個問題。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!