Advertisement
Guest User

Untitled

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