Advertisement
Yakov

FIVT2020.Spring.UniquePtr

May 11th, 2020
1,264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <memory>
  2. #include <iostream>
  3.  
  4. struct A {
  5.   A() { std::cout << "A" << std::endl; }
  6.   ~A() { std::cout << "~A " << b <<  std::endl; }
  7.  
  8.   int b = 0;
  9. };
  10.  
  11. template <class T>
  12. class UniquePtr {
  13. public:
  14.   explicit UniquePtr(T* ptr) : ptr_(ptr) {}
  15.   ~UniquePtr() { delete ptr_; }
  16.  
  17.   // Запрещаем копирование
  18.   UniquePtr(const UniquePtr& other) = delete;
  19.   UniquePtr& operator=(const UniquePtr& other) = delete;
  20.  
  21.   UniquePtr(UniquePtr&& other) : ptr_(other.ptr_) { other.ptr_ = nullptr; }
  22.   UniquePtr& operator=(UniquePtr&& other) {
  23.     std::swap(ptr_, other.ptr_);
  24.     return *this;
  25.   }
  26.  
  27.   UniquePtr& operator=(T* other) {
  28.     if(other != ptr_) {
  29.       delete ptr_;
  30.       ptr_ = other;
  31.     }
  32.  
  33.     return *this;
  34.   }
  35.  
  36.   T& operator* () { return *ptr_;}
  37.   const T& operator* () const { return *ptr_; }
  38.  
  39.   T* operator-> () { return ptr_;}
  40.   const T* operator-> () const { return ptr_;}
  41.  
  42. private:
  43.   T* ptr_ = nullptr;
  44. };
  45.  
  46. void f(bool throw_exception)
  47. {
  48. //  A a;
  49.   UniquePtr<A> pa(new A());
  50.   (*pa).b = 5;
  51.   pa->b = 6;
  52.  
  53.   pa = new A();
  54.  
  55.  
  56.   if(throw_exception)
  57.     throw std::runtime_error("error");
  58. }
  59.  
  60. int main() {
  61.  
  62.   try {
  63.     f(false);
  64.     f(true);
  65.   } catch(const std::exception& exc) {
  66.     std::cout << "g-exception happened: " << exc.what();
  67.   }
  68.  
  69.   return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement