僞智能指針類

#include <iostream>
using namespace std;
class Action
{
public:
    void Do();
};
void Action::Do()
{
    cout<<"Do"<<endl;
}
template <class T>
class A
{
public:
    A( T * pT);
    A(const A&);
    T* operator ->();
    ~A();
private:
    size_t  *pRefCount;
    T       * pT;
};
template <class T>
A<T>::A(T* pT)
{
    this->pRefCount = new size_t(1);
    this->pT = pT;
}
template <class T>
A<T>::A(const A &a)
{
    this->pRefCount = a.pRefCount;
    ++*pRefCount;
}
template <class T>
T* A<T>::operator->()
{
    return this->pT;
}
template <class T>
A<T>::~A()
{
    cout<<"Destructed!"<<endl;
    if(--*this->pRefCount == 0)
    {
        cout<<"Deleted!"<<endl;
        delete pT;
    }
}
int main()
{
    cout << "Hello world!" << endl;
    A<Action> a(new Action());
    A<Action> b = a;
    b->Do();
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章