Advertisement
Guest User

Untitled

a guest
Dec 8th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. template <class T>
  4. class shared_ptr {
  5.  public:
  6.   constexpr shared_ptr() : ptr_(nullptr), counter_(nullptr) {}
  7.  
  8.   shared_ptr(T* ptr) : ptr_(ptr), counter_(new size_t(1)) {}
  9.  
  10.   shared_ptr(const shared_ptr<T>& r) : ptr_(r.ptr_), counter_(r.counter_) {
  11.     ++*(counter_);
  12.   }
  13.  
  14.   void reset() {
  15.     --*(counter_);
  16.     if (*counter_ == 0) {
  17.       delete ptr_;
  18.       delete counter_;
  19.     }
  20.     ptr_ = nullptr;
  21.     counter_ = new size_t(0);
  22.   }
  23.  
  24.   void reset(T* ptr) {
  25.     --*(counter_);
  26.     if (*counter_ == 0) {
  27.       delete ptr_;
  28.       delete counter_;
  29.     }
  30.     ptr_ = ptr;
  31.     counter_ = new size_t(1);
  32.   }
  33.  
  34.   T* get() const { return ptr_; }
  35.  
  36.   T& operator*() const { return *ptr_; }
  37.  
  38.   T* operator->() const { return ptr_; }
  39.  
  40.   long use_count() const { return *counter_; }
  41.  
  42.   bool unique() const { return *counter_ == 1; }
  43.  
  44.   operator bool() const { return ptr_ != nullptr; }
  45.  
  46.   void swap(shared_ptr& r) {
  47.     T* tmp_ptr = ptr_;
  48.     size_t* tmp_counter = counter_;
  49.  
  50.     ptr_ = r.ptr_;
  51.     counter_ = r.counter_;
  52.  
  53.     r.ptr_ = tmp_ptr;
  54.     r.counter_ = tmp_counter;
  55.   }
  56.  
  57.   ~shared_ptr() {
  58.     --*(counter_);
  59.     if (*counter_ == 0) {
  60.       delete ptr_;
  61.       delete counter_;
  62.     }
  63.   }
  64.  
  65.  private:
  66.   T* ptr_;
  67.   size_t* counter_;
  68. };
  69.  
  70. class A {
  71.  public:
  72.   A() { std::cout << "A:A()" << std::endl; }
  73.  
  74.   void method() { std::cout << "A:method()" << std::endl; }
  75.  
  76.   ~A() { std::cout << "~A:A()" << std::endl; }
  77. };
  78.  
  79. int main() {
  80.   shared_ptr<A> a(new A);
  81.   shared_ptr<A> b(a);
  82.   //shared_ptr<int[5]> A;
  83.   shared_ptr<A> c(b);
  84.   std::cout << a.use_count() << std::endl;
  85.   a.reset(new A);
  86.   std::cout << a.use_count() << std::endl;
  87.   std::cout << b.use_count() << std::endl;
  88.   b.reset();
  89.   std::cout << b.use_count() << std::endl;
  90.   std::cout << c.use_count() << std::endl;
  91.   return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement