


#include <iostream>
using namespace std;
template <class T>
class smart_pst{
private:
T* p;
int *count;
smart_pst(T* p);
class Mutex{
private:
pthread_mutex_t m;
public:
Mutex(){
cout<<"Mutex构造函数"<<endl;
pthread_mutex_init(&m,0);
}
void lock(){
pthread_mutex_lock(&m);
}
void unlock(){
pthread_mutex_unlock(&m);
}
};
static Mutex m;
public:
static smart_pst make_ptr();
~smart_pst();
smart_pst(const smart_pst& r);
smart_pst& operator=(const smart_pst& r);
T& operator*();
T* operator->();
smart_pst& operator+(int n);
};
template <typename T>
typename smart_pst<T>::Mutex smart_pst<T>::m;
template <typename T>
smart_pst<T>::smart_pst(T* p):p(p){
count= new int(1);
}
template <typename T>
smart_pst<T>::smart_pst(const smart_pst& r){
this->p=r.p;
this->count=r.count;
(*count)++;
}
template <typename T>
smart_pst<T>::~smart_pst(){
(*count)--;
if((*count)==0){
delete p;
delete count;
}
}
template <typename T>
smart_pst<T>& smart_pst<T>::operator=(const smart_pst& r){
if(this->p==r.p){return *this;}
(*count)--;
if((*count)==0){
delete p;
delete count;
}
p=r.p;
count=r.count;
(*count)++;
return *this;
}
template <typename T>
T& smart_pst<T>::operator*(){
return *p;
}
template <typename T>
T* smart_pst<T>::operator->(){
return p;
}
template <typename T>
smart_pst<T>& smart_pst<T>::operator+(int n){
smart_pst temp=p+n;
return temp;
}
template <typename T>
smart_pst<T> smart_pst<T>::make_ptr(){
m.lock();
smart_pst ptr = new T;
m.unlock();
return ptr;
}
void* thread_main(void* arg){
smart_pst<int> ptr=smart_pst<int>::make_ptr();
}
int main(int argc, const char *argv[])
{
pthread_t id;
pthread_create(&id,0,thread_main,0);
pthread_detach(id);
smart_pst<int> p1 = smart_pst<int>::make_ptr();
return 0;
}
129

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



