fork(2) download
  1. #include <cstddef>
  2. #include <cassert>
  3.  
  4.  
  5. struct object {
  6.  
  7. explicit object(int const data) : data(data) {
  8. ++count;
  9. }
  10.  
  11. ~object() {
  12. --count;
  13. }
  14.  
  15. int data;
  16.  
  17. static std::size_t count;
  18. };
  19.  
  20. std::size_t object::count = 0;
  21.  
  22.  
  23. struct shared_ptr {
  24.  
  25. object * get() const {
  26. if (stored) {
  27. return stored->ptr;
  28. }
  29. return 0;
  30. }
  31.  
  32. std::size_t count() const {
  33. if (stored) {
  34. return stored->count;
  35. }
  36. return 0;
  37. }
  38.  
  39. bool empty() const {
  40. return !get();
  41. }
  42.  
  43. object & operator *() const {
  44. assert(get());
  45. return *get();
  46. }
  47.  
  48. object * operator ->() const {
  49. assert(stored);
  50. return stored->ptr;
  51. }
  52.  
  53.  
  54. shared_ptr() : stored(0) {}
  55.  
  56. explicit shared_ptr(object * const ptr) : stored(new storage(ptr)) {}
  57.  
  58. shared_ptr(shared_ptr const& other) : stored(other.stored) {
  59. increment();
  60. }
  61.  
  62. shared_ptr & operator =(shared_ptr const& other) {
  63. if (stored != other.stored) {
  64. decrement();
  65. stored = other.stored;
  66. increment();
  67. }
  68. return *this;
  69. }
  70.  
  71. ~shared_ptr() {
  72. decrement();
  73. }
  74.  
  75.  
  76. private:
  77. void increment() {
  78. if (stored) {
  79. ++stored->count;
  80. }
  81. }
  82.  
  83. void decrement() {
  84. if (stored && (--stored->count == 0)) {
  85. delete stored->ptr;
  86. delete stored;
  87. stored = 0;
  88. }
  89. }
  90.  
  91.  
  92. struct storage {
  93.  
  94. explicit storage(object * const ptr) : ptr(ptr), count(1) {}
  95.  
  96. object * const ptr;
  97. std::size_t count;
  98. };
  99.  
  100. storage * stored;
  101. };
  102.  
  103.  
  104. int main() {
  105. {
  106. shared_ptr ptr(new object(42));
  107. assert(ptr.count() == 1);
  108. assert(ptr->data == 42);
  109.  
  110. shared_ptr copy(ptr);
  111. assert(copy.count() == 2);
  112. assert(copy->data == 42);
  113.  
  114. shared_ptr empty;
  115. assert(empty.empty());
  116.  
  117. empty = copy;
  118. assert(empty.count() == 3);
  119. assert(empty->data == 42);
  120.  
  121. empty = shared_ptr();
  122. assert(empty.empty());
  123.  
  124. shared_ptr emptyCopy(empty);
  125. assert(emptyCopy.empty());
  126. }
  127.  
  128. assert(object::count == 0);
  129. }
  130.  
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Standard output is empty