Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. // In C++11 we got shared pointer. The standard implementation is much more complete and robust,
  2. // but here I show a barebones version of it to illustrate the main components.
  3. // Behaviour: SharedPTR manages the lifetime of a pointer to a templated object
  4. // SharedPTR can be used to share the pointed object among other SharedPTRs.
  5. // When all of them have given up the pointed object, The SharedPTR deallocates the
  6. // pointed object
  7. // For this we use reference counting. And the main point is that the counter should be a shared object itself
  8. // that would be shared among the SharedPTRs.
  9.  
  10. template<typename T>
  11. struct SharedPTR{
  12. T* ptr = nullptr;
  13.  
  14. // manages the life time count
  15. struct Counter{
  16. int counter = 0;
  17. int inc(){ return counter++;}
  18. int dec(){ return counter--;}
  19. bool isZero(){ return counter == 0;}
  20. };
  21.  
  22. Counter * C = new Counter();
  23.  
  24. explicit SharedPTR(){} // explicit default constructor
  25. explicit SharedPTR(T* t):ptr(t){ C->inc(); } // explicit parameterised default constructor
  26.  
  27. // copy constructor
  28. SharedPTR(const SharedPTR<T>& other){
  29. if (this!=&other){ // avoid copying self
  30. C = other.C;
  31. ptr = other.ptr;
  32. C->inc();
  33. }
  34. }
  35.  
  36. // copy assignment operator
  37. SharedPTR<T>& operator=(const SharedPTR<T>& other){
  38. if (this!=&other){ // avoid copying self
  39. C = other.C;
  40. ptr = other.ptr;
  41. C->inc();
  42. }
  43. return *this;
  44. }
  45.  
  46. ~SharedPTR(){
  47. C->dec();
  48. if(C->isZero()){
  49. delete ptr;
  50. delete C;
  51. }
  52. }
  53. };
  54.  
  55.  
  56. struct dummy{
  57. dummy(){ std::cout << "constructed\n"; }
  58. ~dummy(){ std::cout << "destructed\n"; }
  59. };
  60.  
  61. int main(){
  62. SharedPTR<dummy> p1;
  63. {
  64. SharedPTR<dummy> sp(new dummy());
  65. p1 = sp;
  66. }
  67. std::cout << "here\n";
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement