troubleasy

导航

 
shared_ptr实现
template<class T>
class SharedPtr{
    T*_ptr;
    int*_pcount;
public:
    SharedPtr(T*q):_pre(q),_pcount(new int(1)){}
    SharedPtr(const SharedPtr<T>&sp):_ptr(sp.str),_pcount(s._pcount){*(_pcount)++;}
    T& operator*()
    {
     return *_ptr;   
    }
    T*operator->()
    {
    return _ptr;
    }
    SharedPtr<T>& operator=(const SharedPtr<T>&s)
    {
        if(this!=s)
        {
            if(--(*(this->_pcount)==0)
               {
                delete _ptr;
                delete _pcount;
               }
        
        _ptr=s._ptr;
        _pcount=s._pcount;
        }
        return this;
    }
    ~SharedPtr(){
        if(--(*(this->_pcount)==0)
               {
                delete _ptr;
                delete _pcount;
               }
    }
    }
};
View Code
#include <iostream>
#include <memory>

struct C { int a; int b; };

int main () {
  std::shared_ptr<C> p1;
  std::shared_ptr<C> p2 (new C);
  std::shared_ptr<int> p3 (new int);
  std::shared_ptr<int> p4 (new int (100)); 
  *p3 = *p4 * 2;
  p1 = p2;

  p1->a = 10;
  p2->b = 20;

  if (p1) std::cout << "p1: " << p1->a << ' ' << p1->b << '\n';
  if (p2) std::cout << "p2: " << p2->a << ' ' << p2->b << '\n';
  std::cout << "p3: " << *p3 << '\n';
  std::cout << "p4: " << *p4 << '\n';
  return 0;
View Code
输出结果:
p1:10 20
p2:10 20
p3:200
p4:100
注意:1.shared_ptr互相引用的问题,采用weak_ptr解决;
2.不可以用同一个指针初始化多个智能指针
int*p=new int;
shared_ptr<int>p1(p);
//shared_ptr<int>p2(p);(错误)
shared_ptr<int>p2(p1);
建议采用make_shared初始化shared_ptr
shared_ptr<int>p3=make_shared<int>(10);


posted on 2021-10-13 02:17  troubleasy  阅读(77)  评论(0)    收藏  举报