C++自动指针实现

来源:互联网 发布:优化后讨鬼传2 psv画质 编辑:程序博客网 时间:2024/06/10 22:25

auto_ptr的实现

以下代码摘录自More Effective C++

auto_ptr.h

#ifndef AUTO_PTR_H#define AUTO_PTR_Htemplate<typename T>class auto_ptr{    public :        //使用explicit关键字避免隐式转换        explicit auto_ptr(T* p=0);        ~auto_ptr();        //使用另一个类型兼容的auto_ptr来初始化一个新的auto_ptr        template<typename U>        auto_ptr(auto_ptr<U>& rhs);        template<typename U>        auto_ptr<T>& operator=(auto_ptr<U>& rhs);        T& operator*() const;        T* operator->() const;        //返回原始对象的指针        T* get() const;        //放弃指针的所以权        T* release();        //删除原有指针并获得指针的p的所有权        void reset(T* p=0);    private:        T* pointee;};template<typename T>auto_ptr<T>::auto_ptr(T* p)    :pointee(p){}template<typename T>    template<typename U>auto_ptr<T>::auto_ptr(auto_ptr<U>& rhs)    :pointee(rhs.release()){}template<typename T>auto_ptr<T>::~auto_ptr(){    delete pointee;}template<typename T>    template<typename U>auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr<U>& rhs){    if(this!=&rhs)        reset(rhs.release());    return *this;}template<typename T>T& auto_ptr<T>::operator*() const{    return *pointee;}template<typename T>T* auto_ptr<T>::operator->() const{    return pointee;}template<typename T>T* auto_ptr<T>::get() const{    return pointee;}template<typename T>T* auto_ptr<T>::release(){    T* oldpointee=pointee;    pointee=0;    return oldpointee;}template<typename T>void auto_ptr<T>::reset(T* p){    if(pointee!=p)    {        delete pointee;        pointee=p;    }}#endif

用来测试的Item类

//Item.h#ifndef ITEM_H#define ITEM_Hclass Item{public:    Item(void);    ~Item(void);    void PrintContent() const;};#endif//Item.cppusing std::cout;using std::endl;Item::Item(void){}Item::~Item(void){    cout<<"Destorying....."<<endl;}void Item::PrintContent() const{    cout<<"Here is the content"<<endl;}

main.cpp

#include <iostream>#include "auto_ptr.h"#include "Item.h"using std::cout;int main(){    auto_ptr<Item> itemPtr(new Item);    itemPtr->PrintContent();    auto_ptr<Item> itemPtr2(itemPtr);    itemPtr2->PrintContent();    return 0;}

运行程序,可以看到建在堆上的Item对象自动释放了,因为auto_ptr对象析构时将指针pointee delete了,同时结果如下:

Here is the content
Here is the content
Destorying.....

程序只会输出一句Destorying.....,因为在构造itemPtr2时,itemPtr的成员pointee指向的Item已经转交给了itemPtr2中的指针,

所以最后只会看到一句Destorying.....,也就是只有一个Item对象析构了...