實作 smart pointer

實作 smart pointer

這是模仿 std::tr1::shared_ptr 的實作

將一個new出來的實體包覆在一個物件中

然後複寫原本的複製建構式與operator

加入一個靜態計數器去記錄被複製的次數

 

#include <iostream>
#include <stdio.h>
#include <stdarg.h>
#include <string>
#include <vector>

template <class T> class MyPtr
{
private:
T* _ptr;

// a static counter how many you copy
static int iCount;

public:
MyPtr(T* ptr_)
{
iCount++;
_ptr = ptr_;
}

// redefine the clone construct
MyPtr(const MyPtr& self_)
{
iCount++;
_ptr = self_.get();
}

// redefine the colne operator
void operator = (const MyPtr& self_)
{
iCount++;
_ptr = self_.get();
}

~MyPtr()
{
iCount--;
if(iCount==0)
delete _ptr;
}

T* get() const {return _ptr;}
int count(){return iCount;}
};

template <class T> int MyPtr<T>::iCount = 0;


class Test1
{
public:
Test1(){std::cout<<"test 1 constructed"<<std::endl;}
~Test1(){std::cout<<"test 1 destructed"<<std::endl;}
void print(){std::cout<<"print was called in the test 1"<<std::endl;}
};

class Test2
{
public:
Test2(){std::cout<<"test 2 constructed"<<std::endl;}
~Test2(){std::cout<<"test 2 destructed"<<std::endl;}
void print(){std::cout<<"print was called in the test 2"<<std::endl;}
};

typedef MyPtr<Test1> Test1_Ptr;
typedef MyPtr<Test2> Test2_Ptr;
typedef std::vector<Test2_Ptr> ArrTest2_Ptr;

ArrTest2_Ptr arrTest2_Ptr;

void Program2(Test1_Ptr test1_Ptr_)
{
test1_Ptr_.get()->print();

arrTest2_Ptr.at(0).get()->print();
arrTest2_Ptr.erase(arrTest2_Ptr.begin());
}

void Program1()
{
Test2_Ptr test2_Ptr(new Test2());
Test1_Ptr test1_Ptr(new Test1());

arrTest2_Ptr.push_back(test2_Ptr);

Program2(test1_Ptr);
}

int main(int argc, char** argp)
{
Program1();

}