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.

81 lines
2.1 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * counted_ptr - simple reference counted pointer.
  3. *
  4. * The is a non-intrusive implementation that allocates an additional
  5. * int and pointer for every counted object.
  6. */
  7. #ifndef COUNTED_PTR_H
  8. #define COUNTED_PTR_H
  9. #define NO_MEMBER_TEMPLATES
  10. /* For ANSI-challenged compilers, you may want to #define
  11. * NO_MEMBER_TEMPLATES or explicit */
  12. template <class X> class counted_ptr
  13. {
  14. public:
  15. typedef X element_type;
  16. explicit counted_ptr(X* p = 0) // allocate a new counter
  17. : itsCounter(0) {if (p) itsCounter = new counter(p);}
  18. ~counted_ptr()
  19. {release();}
  20. counted_ptr(const counted_ptr& r) throw()
  21. {acquire(r.itsCounter);}
  22. counted_ptr& operator=(const counted_ptr& r)
  23. {
  24. if (this != &r) {
  25. release();
  26. acquire(r.itsCounter);
  27. }
  28. return *this;
  29. }
  30. #ifndef NO_MEMBER_TEMPLATES
  31. template <class Y> friend class counted_ptr<Y>;
  32. template <class Y> counted_ptr(const counted_ptr<Y>& r) throw()
  33. {acquire(r.itsCounter);}
  34. template <class Y> counted_ptr& operator=(const counted_ptr<Y>& r)
  35. {
  36. if (this != &r) {
  37. release();
  38. acquire(r.itsCounter);
  39. }
  40. return *this;
  41. }
  42. #endif // NO_MEMBER_TEMPLATES
  43. X& operator*() const throw() {return *itsCounter->ptr;}
  44. X* operator->() const throw() {return itsCounter->ptr;}
  45. X* get() const throw() {return itsCounter ? itsCounter->ptr : 0;}
  46. bool unique() const throw()
  47. {return (itsCounter ? itsCounter->count == 1 : true);}
  48. private:
  49. struct counter {
  50. counter(X* p = 0, unsigned c = 1) : ptr(p), count(c) {}
  51. X* ptr;
  52. unsigned count;
  53. }* itsCounter;
  54. void acquire(counter* c) throw()
  55. { // increment the count
  56. itsCounter = c;
  57. if (c) ++c->count;
  58. }
  59. void release()
  60. { // decrement the count, delete if it is 0
  61. if (itsCounter) {
  62. if (--itsCounter->count == 0) {
  63. delete itsCounter->ptr;
  64. delete itsCounter;
  65. }
  66. itsCounter = 0;
  67. }
  68. }
  69. };
  70. #endif // COUNTED_PTR_H