SHARE
TWEET

Untitled

a guest Mar 19th, 2019 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <exception>
  3. #include <functional>
  4. #include <optional>
  5. #include <cstddef>
  6. #include <memory>
  7.  
  8. template <typename T, typename del = std::default_delete<T>>
  9. class UniquePtr {
  10. private:
  11.     std::tuple<T*, del> ptr;
  12.  
  13. public:
  14.     UniquePtr() {
  15.         std::get<0>(ptr) = nullptr;
  16.     }
  17.  
  18.     UniquePtr(T* smth) {
  19.         std::get<0>(ptr) = smth;
  20.     }
  21.  
  22.     UniquePtr(UniquePtr<T>&& another) noexcept {
  23.         std::get<0>(ptr) = another.ptr;
  24.         std::get<0>(another.ptr) = nullptr;
  25.     }
  26.  
  27.     UniquePtr(T* smth, del deleter) {
  28.         std::get<0>(ptr) = smth;
  29.         std::get<1>(ptr) = deleter;
  30.     }
  31.  
  32.     UniquePtr& operator=(std::nullptr_t it_is_nullptr) {
  33.         std::get<1>(ptr)(std::get<0>(ptr));
  34.         std::get<0>(ptr) = it_is_nullptr;
  35.         return *this;
  36.     }
  37.  
  38.     UniquePtr& operator= (UniquePtr<T>&& another) noexcept {
  39.         std::swap(std::get<0>(another.ptr), std::get<0>(ptr));
  40.         another.std::get<1>(ptr)(std::get<0>(another.ptr));
  41.         another.std::get<0>(ptr) = nullptr;
  42.         return *this;
  43.     }
  44.  
  45.     T& operator*() const {
  46.         return *std::get<0>(ptr);
  47.     }
  48.  
  49.     T* operator->() const noexcept {
  50.         return std::get<0>(ptr);
  51.     }
  52.  
  53.     T * release() noexcept {
  54.         T * to_give = nullptr;
  55.         std::swap(to_give, std::get<0>(ptr));
  56.         return to_give;
  57.     }
  58.  
  59.     void reset(T * ptr_) noexcept {
  60.         std::get<1>(ptr)(std::get<0>(ptr));
  61.         std::get<0>(ptr) = ptr_;
  62.     }
  63.  
  64.     void swap(UniquePtr& other) noexcept {
  65.         std::swap(std::get<0>(other.ptr), std::get<0>(ptr));
  66.     }
  67.  
  68.     T * get() const noexcept {
  69.         return std::get<0>(ptr);
  70.     }
  71.  
  72.     explicit operator bool() const noexcept {
  73.         return static_cast<bool>(std::get<0>(ptr));
  74.     }
  75.  
  76.     del& get_deleter() {
  77.         return std::get<1>(ptr);
  78.     }
  79.  
  80.     const del& get_deleter() const {
  81.         return std::get<1>(ptr);
  82.     }
  83.  
  84.     ~UniquePtr() {
  85.         std::get<1>(ptr)(std::get<0>(ptr));
  86.     }
  87. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top