6.3作业

 

 #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;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值