Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. #include <cstddef>
  2. #include <iostream>
  3.  
  4. template <typename T>
  5. class UniquePtr {
  6. private:
  7. T *ptr;
  8.  
  9. public:
  10. UniquePtr(): ptr(nullptr) {
  11. // std::cout << "UniqPtr()\n";
  12. }
  13.  
  14. UniquePtr(T *ptr): ptr(ptr) {
  15. // std::cout << "UniqPtr(T *ptr)\n";
  16. }
  17.  
  18. UniquePtr(UniquePtr<T> &&oth) {
  19. // std::cout << "UniqPtr(&&oth)\n";
  20. *this = nullptr;
  21. std::swap(ptr, oth.ptr);
  22. }
  23.  
  24. UniquePtr(const UniquePtr &oth) = delete;
  25.  
  26. UniquePtr& operator=(const UniquePtr<T> &oth) = delete;
  27.  
  28. UniquePtr& operator=(UniquePtr<T> &&oth) {
  29. // std::cout << "operator=(&&oth)\n";
  30. *this = nullptr;
  31. std::swap(ptr, oth.ptr);
  32. return *this;
  33. }
  34.  
  35. UniquePtr& operator=(std::nullptr_t) {
  36. delete ptr;
  37. ptr = nullptr;
  38. return *this;
  39. }
  40.  
  41. T& operator*() noexcept {
  42. return *ptr;
  43. }
  44.  
  45. const T& operator*() const noexcept {
  46. return *ptr;
  47. }
  48.  
  49. T* operator->() const {
  50. return ptr;
  51. }
  52.  
  53. T* release() noexcept {
  54. T *free = ptr;
  55. ptr = nullptr;
  56. return free;
  57. }
  58.  
  59. void reset(T * p) {
  60. *this = nullptr;
  61. ptr = p;
  62. }
  63.  
  64. void swap(UniquePtr &oth) noexcept {
  65. std::swap(ptr, oth.ptr);
  66. }
  67.  
  68. T* get() const {
  69. return ptr;
  70. }
  71.  
  72. explicit operator bool() const noexcept {
  73. return ptr != nullptr;
  74. }
  75.  
  76. ~UniquePtr() {
  77. // std::cout << "~UniqPtr()\n";
  78. delete ptr;
  79. }
  80. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement