Advertisement
Guest User

Untitled

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