Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. using namespace std;
  2.  
  3. template <typename T>
  4. class SharedPtr {
  5. private:
  6. T * ptr = nullptr;
  7. int * counter = new int(1);
  8.  
  9. public:
  10. SharedPtr() {
  11. *counter = 1;
  12. }
  13. SharedPtr(T* input) {
  14. *counter = 1;
  15. ptr = input;
  16. }
  17. SharedPtr(const SharedPtr& input) {
  18. counter = input.counter;
  19. *counter += 1;
  20. ptr = input.ptr;
  21. }
  22. SharedPtr(SharedPtr&& other) noexcept {
  23. ptr = other.ptr;
  24. other.ptr = nullptr;
  25. counter = other.counter;
  26. *counter += 1;
  27. }
  28. SharedPtr operator=(T * input) noexcept {
  29. *counter -= 1;
  30. if (!(*counter)) {
  31. delete ptr;
  32. }
  33. ptr = input;
  34. counter = new int(1);
  35. return *this;
  36. }
  37. SharedPtr& operator =(const SharedPtr<T>& other) noexcept {
  38. *counter -= 1;
  39. if (!(*counter)) {
  40. delete ptr;
  41. }
  42. ptr = other.ptr;
  43. counter = other.counter;
  44. *counter += 1;
  45. return *this;
  46. }
  47. SharedPtr& operator =(SharedPtr<T>&& other) noexcept {
  48. *counter -= 1;
  49. if (!(*counter)) {
  50. delete ptr;
  51. }
  52. ptr = other.ptr;
  53. counter = other.counter;
  54. *counter += 1;
  55. return *this;
  56. }
  57. T* operator ->() const noexcept {
  58. return ptr;
  59. }
  60. T& operator*() const noexcept {
  61. return *ptr;
  62. }
  63. T& operator*() noexcept {
  64. return *ptr;
  65. }
  66. void reset(T* t) {
  67. --(*counter);
  68. if (!(*counter)) {
  69. delete ptr;
  70. }
  71. ptr = t;
  72. counter = new int(1);
  73. }
  74. void swap(SharedPtr<T>& other) noexcept {
  75. std::swap(ptr, other.ptr);
  76. std::swap(counter, other.counter);
  77. }
  78. T* get() const noexcept {
  79. return ptr;
  80. }
  81. explicit operator bool() const {
  82. if (ptr) {
  83. return true;
  84. }
  85. return false;
  86. }
  87. ~SharedPtr() {
  88. --(*counter);
  89. if (!(*counter)) {
  90. delete ptr;
  91. }
  92. }
  93. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement