#include <pthread.h>
#pragma comment(lib,"x86/pthreadVC2.lib")
using namespace std;
template <typename T>
class Shared_ptr {
public:
Shared_ptr(){
count = 0;
_ptr = (T*)0;
pthread_mutex_init(&mutex, NULL);
}
Shared_ptr(T* p){
count = new int(1);
_ptr = p;
pthread_mutex_init(&mutex, NULL);
}
Shared_ptr(Shared_ptr<T>& other){
pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex);
count = &(++ *other.count);
_ptr = other._ptr;
pthread_mutex_unlock(&mutex);
}
T* operator->(){
return _ptr;
}
T& operator*() {
return *_ptr;
}
Shared_ptr<T>& operator=(Shared_ptr<T>& other) {
if (this == &other){
return *this;
}
++(*other.count);
pthread_mutex_lock(&mutex);
if (this->_ptr && 0 == --(*this->count)){
delete count;
delete _ptr;
cout << "delete ptr =" << endl;
}
this->_ptr = other._ptr;
this->count = other.count;
pthread_mutex_unlock(&mutex);
return *this;
}
~Shared_ptr(){
if (_ptr && --(*count) == 0){
pthread_mutex_lock(&mutex);
delete count;
delete _ptr;
pthread_mutex_unlock(&mutex);
cout << "Delete ptr" << endl;
}
}
int getRef() {
return *count;
}
private:
int* count;
T* _ptr;
pthread_mutex_t mutex;
};
int main(int argc, const char * argv[])
{
Shared_ptr<string> pstr(new string("abc"));
cout << "Pstr:" << pstr.getRef() << " " << *pstr << endl;
Shared_ptr<string> pstr2(pstr);
cout << "Pstr:" << pstr.getRef() << " "<< *pstr << endl;
cout << "pstr2:" << pstr2.getRef() << " "<< *pstr2 << endl;
return 0;
}