AbaKus – a complex calculator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

123 lines
2.5 KiB

  1. #ifndef ABAKUS_SHARED_PTR_H
  2. #define ABAKUS_SHARED_PTR_H
  3. /*
  4. * sharedptr.h - part of abakus
  5. * Copyright (C) 2004, 2005 Michael Pyne <michael.pyne@kdemail.net>
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include <kdebug.h>
  22. template <class T>
  23. class SharedPtr
  24. {
  25. public:
  26. typedef T value_type;
  27. class Data
  28. {
  29. public:
  30. Data(T *ptr = 0, unsigned refCount = 1) : m_ptr(ptr), m_refCount(refCount)
  31. {
  32. }
  33. void deref()
  34. {
  35. --m_refCount;
  36. if(!m_refCount) {
  37. delete m_ptr;
  38. m_ptr = 0;
  39. }
  40. }
  41. void ref()
  42. {
  43. ++m_refCount;
  44. }
  45. T *ptr() { return m_ptr; }
  46. const T* ptr() const { return m_ptr; }
  47. unsigned refCount() const { return m_refCount; }
  48. private:
  49. T *m_ptr;
  50. unsigned m_refCount;
  51. };
  52. SharedPtr() : m_data(new Data)
  53. {
  54. }
  55. SharedPtr(T* ptr) : m_data(new Data(ptr))
  56. {
  57. }
  58. SharedPtr(const SharedPtr<T> &other) : m_data(other.m_data)
  59. {
  60. m_data->ref();
  61. }
  62. ~SharedPtr()
  63. {
  64. m_data->deref();
  65. }
  66. SharedPtr<T> &operator=(const SharedPtr<T> &other)
  67. {
  68. if(&other == this)
  69. return *this;
  70. m_data->deref();
  71. m_data = other.m_data;
  72. m_data->ref();
  73. return *this;
  74. }
  75. T *operator ->()
  76. {
  77. return m_data->ptr();
  78. }
  79. const T *operator ->() const
  80. {
  81. return m_data->ptr();
  82. }
  83. T &operator *()
  84. {
  85. return *m_data->ptr();
  86. }
  87. const T& operator *() const
  88. {
  89. return *m_data->ptr();
  90. }
  91. bool isNull() const { return m_data->ptr() == 0; }
  92. unsigned refCount() const { return m_data->refCount(); }
  93. private:
  94. Data *m_data;
  95. };
  96. #endif /* ABAKUS_SHARED_PTR_H */
  97. // vim: set et ts=8 sw=4: