智能指针的实现是C++中的热点,它哦功能就是动态分配对象以及当对象不再需要时自动执行清理,因此不必担心内存泄露问题。智能指针经常出现在各种C++面试中,要有考生说出智能指针的优缺点,甚至让求职者实现一个自己的智能指针。在C++编程领域里,有两种智能指针的实现:auto_ptr和shared_ptr.
auto_ptr<T> ptr(new Y)
shared_ptr<T> ptr(new X)
下面为智能指针的示例:
#include<iostream>
using namespace std;
template <class T> class SmartPtr
{
public:
SmartPtr(T * realPtr=0):pointee(realPtr){};
SmartPtr(SmartPtr<T> &rhs);
~SmartPtr()
{
delete pointee;
}
SmartPtr &operator=(SmartPtr<T> &rhs);
T* operator->() const;
T& operator*() const;
bool operator!() const;
private:
T* pointee;
};
template<class T> SmartPtr<T>::SmartPtr(SmartPtr<T> &rhs)
{
pointee=rhs.pointee;
rhs.pointee=NULL;
}
template<class T> SmartPtr<T> &SmartPtr<T>::operator=(SmartPtr<T> &rhs)
{
if(this==&rhs)
return this;
delete pointee;
pointee==rhs.pointee;
rhs.pointee=0;
return *this;
}
template<class T> T* SmartPtr<T>::operator->() const
{
return pointee;
}
template<class T> T & SmartPtr<T>::operator *() const
{
return *pointee;
}
template<class T> bool SmartPtr<T>::operator!() const
{
return pointee==NULL;
}