标准库shared_ptr智能指针的实现

时间:2022-05-10 16:27:40

目前测试功能正常。若有不完善的地方在改进吧。时候不早了睡觉去,哎,翘课会被抓,不冒险了。晚安全世界O(∩_∩)O

 /*************************************************************************
*my shared_ptr: share_ptr
*author:ERIC
*blog:http://www.ilovecpp.com
*time:2015-5-28 01:36:43
*************************************************************************/ template <typename T> class share_ptr {
private:
T* __ptr;
int* __pcounts;
public:
share_ptr(T* p= NULL);
share_ptr(const share_ptr<T>& src);
share_ptr& operator=(share_ptr<T>& src);
~share_ptr();
operator bool() const;//支持if(p)形式
T* operator-> () const;
T& operator*() const;
T* get() const;
int use_counts() const;//返回引用计数
bool unique() const;//当前智能指针是否唯一
void swap(share_ptr& rhs);//交换,成员函数
template <typename Type>//友元函数,交换两个智能指针
friend void swap(share_ptr<Type>& lhs,share_ptr<Type>& rhs);
}; template<typename T>
share_ptr<T>::share_ptr(T* p)
:__ptr(p),__pcounts(new int())
{
if(__ptr)
*__pcounts = ;
} template<typename T>
share_ptr<T>::~share_ptr()
{
--*__pcounts;
if(*__pcounts == )
{//空智能指针这里delete __ptr也安全,delete NULL;
delete __pcounts;
delete __ptr;
}
} /*__ptr(new T(src)) 很重要 ,如果直接__ptr(new T)
*会由于T类没有默认构造函数而出错
*测试的时候才发现这个问题的
*/
template<typename T>
share_ptr<T>::share_ptr (const share_ptr<T>& src)
:__pcounts(new int),__ptr(new T(src))
{
++*src.__pcounts;
__ptr = src.__ptr;
__pcounts = src.__pcounts;
} template <typename T>
share_ptr<T>& share_ptr<T>::operator= (share_ptr<T>& src)
{
--*__pcounts;
//如果是空智能指针的话 __pcounts == -1,那块内存也得释放
if(*__pcounts == || *__pcounts == -)
delete __pcounts;
++*src.__pcounts;
__ptr = src.__ptr;
__pcounts = src.__pcounts;
return *this;
} //支持if(p)这样的操作
template<typename T>
share_ptr<T>::operator bool() const
{
return __ptr;
} template<typename T>
T* share_ptr<T>::operator->() const
{
return __ptr;
} template<typename T>
T& share_ptr<T>::operator*() const
{
return *__ptr;
} template<typename T>
T* share_ptr<T>::get() const
{
return __ptr;
} template<typename T>
int share_ptr<T>::use_counts() const
{
return *__pcounts;
} template<typename T>
bool share_ptr<T>::unique() const
{
if(*__pcounts == )
return true;
else
return false;
} template<typename T>
void share_ptr<T>::swap(share_ptr<T>& rhs)
{
T* tmpPtr = rhs.__ptr;
rhs.__ptr = __ptr;
__ptr = tmpPtr;
int* tmpPcounts = rhs.__pcounts;
rhs.__pcounts = __pcounts;
__pcounts = tmpPcounts;
} template<typename T>
void swap(share_ptr<T>& lhs,share_ptr<T>& rhs)
{
T* tmpPtr = rhs.__ptr;
rhs.__ptr = lhs.__ptr;
lhs.__ptr = tmpPtr;
int* tmpPcounts = rhs.__pcounts;
rhs.__pcounts = lhs.__pcounts;
lhs.__pcounts = tmpPcounts;
} //c++11 make_shared<T>(args)
template<typename T>
share_ptr<T> make_share(T args)
{
return new T(args);
}