题目:《程序员面试金典 (第5版)》P279
编写一个智能指针类。智能指针是一种数据类型,一般用模板实现,模拟指针行为的同时还提供自动垃圾回收机制。它会自动记录SmartPointer<T*>对象的引用计数,一旦T类型对象的引用计数为零,就会释放对象。
template<class T> class SmartPointer
{
public:
SmartPointer(T* p);
SmartPointer(SmartPointer<T> &other);
SmartPointer<T>& operator=(SmartPointer<T> &other);
T GetValue();
~SmartPointer();
protected:
void remove();
T* mptr;
int* count;
};
template<class T> SmartPointer<T>::SmartPointer(T* p)
{
mptr = p;
count = new int;
*count = 1;
}
template<class T> SmartPointer<T>::SmartPointer(SmartPointer<T> &other)
{
mptr = other.mptr;
*other.count += 1;
count = other.count;
}
template<class T> SmartPointer<T>& SmartPointer<T>::operator=(SmartPointer<T> &other)
{
if (*this == other)
return *this;
if (*count > 0)
{
remove();
}
mptr = other.mptr;
*other.count += 1;
count = other.count;
return *this;
}
template<class T> T SmartPointer<T>::GetValue()
{
return *mptr;
}
template<class T> SmartPointer<T>::~SmartPointer()
{
remove();
}
template<class T> void SmartPointer<T>::remove()
{
*count -= 1;
if (*count <= 0)
{
delete mptr;
delete count;
mptr = nullptr;
count = nullptr;
}
}
在《C++高级编程》第21章里,有另一个更完善的智能指针。如下所示:
template< typename T>
class SmartPointer
{
public:
SmartPointer(T* point);
SmartPointer(const SmartPointer<T>& rch);
SmartPointer& operator=(const SmartPointer<T>& rch);
virtual ~SmartPointer();
T& operator*();
const T& operator*()const;
protected:
static unordered_map<T*, int> used;
T *mPtr;
void finalpoint();
void initpoint(T* point);
};
//这一行初始化静态成员数据used,没有这一行会报错
template< typename T> unordered_map<T*, int> SmartPointer<T>::used;
template< typename T> SmartPointer<T>::SmartPointer(T* point)
{
initpoint(point);
}
template< typename T> SmartPointer<T>::SmartPointer(const SmartPointer<T>& rch)
{
initpoint(rch.mPtr);
}
template< typename T> SmartPointer<T>& SmartPointer<T>::operator=(const SmartPointer<T>& rch)
{
if (this == &rch)
return *this;
finalpoint();
initpoint(rch.mPtr);
return *this;
}
template< typename T> SmartPointer<T>::~SmartPointer()
{
finalpoint();
}
template< typename T> void SmartPointer<T>::initpoint(T* point)
{
mPtr =point;
if (used.find(point) != used.end())
{
cout << "添加 " << point << endl;
used[point]++;
}
else
{
cout << "新建 " << point << endl;
used[point] = 1;
}
}
template< typename T> void SmartPointer<T>::finalpoint()
{
if (used.find(mPtr) == used.end())
{
throw std::runtime_error("ERROR:Missing entry in map!");
}
used[mPtr]--;
if (used[mPtr] == 0)
{
cout << "删除 " << mPtr << endl;
used.erase(mPtr);
delete mPtr;
}
mPtr = nullptr;
}
template< typename T> T& SmartPointer<T>::operator*()
{
cout << "no const*" << endl;
return *mPtr;
}
template< typename T> const T& SmartPointer<T>::operator*()const
{
cout << "const*" << endl;
return *mPtr;
}
//主函数代码
//{
// int * l = new int(8);
// SmartPointer<int> p1(l);
// SmartPointer<int> p2(l);
// *p1 = 20;
// int b = *p2;
// cout << *p2 << endl;
//}