智能指针
智能指针就是利用构造函数构造,出了域之后利用类的性质自动调用析构函数析构,解决了指针的内存泄漏问题,省去抛出异常语句
指针
template<class T>
class AutoPtr
{
public:
AutoPtr( T* ptr )
:_ptr( ptr)
{
}
~AutoPtr()
{
if (_ptr != NULL)
{
cout << "delete" << _ptr << endl;
delete _ptr;
_ptr = NULL;
}
}
AutoPtr( AutoPtr<T >&ap)
:_ptr( ap._ptr)
{
ap._ptr = NULL;//管理权转移
}
AutoPtr<T >&operator=(AutoPtr< T>&ap )
{
if (this != &ap)//检测是否自赋值
{
cout << "delete=" << _ptr << endl;
delete _ptr;//删除指向空间
_ptr = ap._ptr;//指向另一块空间
ap._ptr = NULL;//指针指向空
return *this ;
}
}
T& operator*()
{
return *_ptr;
}
T*operator->()
{
return _ptr;
}
private:
T* _ptr;
};
struct A
{
int _a;
};
int main()
{
AutoPtr<int > ap1(new int(1));
AutoPtr<int > ap2(ap1);
AutoPtr<int > ap3(new int(2));
ap3 = ap2;
*ap3 = 3;
AutoPtr<A > ap4(new A);
ap4->_a = 10;
return 0;
}
template<class T>
class ScopedPtr
{
public:
ScopedPtr( T* ptr )
:_ptr( ptr)
{
}
~ScopedPtr()
{
if (_ptr != NULL)
{
delete _ptr;
}
}
T&operator*()
{
return *_ptr;
}
T*operator->()
{
return _ptr;
}
protected:
ScopedPtr( ScopedPtr<T >&sp);
ScopedPtr operator=(ScopedPtr <T>&sp);
//只声明(声明后系统不会自动生成)不实现,且属于保护成员(或声明为私有成员),故在类外成员不能实现赋值语句,类外也不能实现这个函数
private:
T* _ptr;
};
struct A
{
int _a;
};
int main()
{
ScopedPtr<int >sp1(new int(1));
//ScopedPtr<int>sp2(sp1);
*sp1 = 10;
ScopedPtr<A >sp2(new A);
sp2->_a = 10;
//ScopedPtr<int>sp2=sp1;
return 0;
}
scoped数组
template<class T>
class ScopedArray
{
public:
ScopedArray( T *ptr )
: _ptr( ptr)
{}
~ScopedArray()
{
if (_ptr!=NULL )
{
delete[]_ptr;
}
}
T& operator[](size_t index)
{
return _ptr[index ];
}
protected:
ScopedArray( ScopedArray<T >&sp);
ScopedArray<T >&operator=(ScopedArray< T>&sp);
private:
T *_ptr;
};
template<class T>
class SharedPtr
{
public:
SharedPtr( T*ptr )
:_ptr( ptr)
, _pCount( new int (1))
{}
~SharedPtr()
{
DeleteCount();
}
SharedPtr( const SharedPtr <T>& sp)
:_ptr( sp._ptr)
, _pCount( sp._pCount)
{
++(*_pCount);
}
SharedPtr<T >& operator=(const SharedPtr< T>& sp )
{
//1.自赋值
//2.两个对象管理同一块空间
//3.两个对象两个空间
if (_ptr != sp ._ptr)
{
DeleteCount();
_ptr = sp._ptr;
_pCount = sp._pCount;
++(*_pCount);
}
return*this;
}
/*
swap(_ptr, sp._ptr);
swap(_pCount, sp._pCount);
*/
T &operator*()
{
return *_ptr;
}
T *operator->()
{
return _ptr;
}
private:
void DeleteCount()
{
if (--(*_pCount) == 0)
{
delete _ptr;
delete _pCount;
}
}
private:
T* _ptr;
int* _pCount;
};
struct A
{
int _a;
};
int main()
{
SharedPtr<int > sp1(new int(1));
SharedPtr<int >sp2(new int(2));
SharedPtr<int >sp3(sp1);
sp3 = sp2;
SharedPtr<int >sp4(new int(3));
*sp4 = 10;
SharedPtr<A >sp5(new A);
sp5->_a = 20;
getchar();
return 0;
}
转载于:https://blog.51cto.com/10797127/1758993