auto_ptr是C++标准库里的类,它接受一个类型形参的模板,为动态分配的对象提供异常安全。其实,它的核心思想是:用一个对象存储需要被自动释放的资源,然后依靠对象的析构函数来释放资源,这是《More Effective C++》中的解释。下面给出它的一个简单实现,摘自《More Effective C++》附录,做了部分修改,不支持不同类型的转换。已通过VC6.0编译。
#include <iostream>
using namespace std;
template<class T>
class auto_ptr {
public:
explicit auto_ptr(T *p = 0): pointee(p) {}
auto_ptr(auto_ptr<T>& rhs): pointee(rhs.release()) {}
~auto_ptr() { delete pointee; }
auto_ptr<T>& operator=(auto_ptr<T>& rhs)
{
if (this != &rhs) reset(rhs.release());
return *this;
}
T& operator*() const { return *pointee; }
T* operator->() const { return pointee; }
T* get() const { return pointee; }
T* release()
{
T *oldPointee = pointee;
pointee = 0;
return oldPointee;
}
void reset(T *p = 0)
{
if (pointee != p) {
delete pointee;
pointee = p;

本文探讨了C++中的auto_ptr,它用于自动管理动态内存。通过构造函数、析构函数、赋值操作以及解引用操作的讨论,展示了auto_ptr如何工作并确保异常安全性。同时,文章指出了使用auto_ptr可能遇到的问题,如不能保存指向静态或动态分配数组的指针,以及避免在容器中存储auto_ptr等。


被折叠的 条评论
为什么被折叠?



