Advertisement
Kira5005

Untitled

Dec 5th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1.  
  2. #include "matrix.hpp"
  3. #include "shared_ptr.hpp"
  4.  
  5.  
  6. shared_ptr::Storage::Storage(Matrix* mtx) {
  7.     data_ = mtx;
  8.     ref_count_ = 1;
  9. }
  10.  
  11. shared_ptr::Storage::~Storage() {
  12.     data_=nullptr;
  13.     ref_count_ = 0;
  14. }
  15.  
  16. void shared_ptr::Storage::incr() {
  17.     if (this != nullptr) {
  18.         ref_count_++;
  19.     }
  20. }
  21.  
  22. void shared_ptr::Storage::decr() {
  23.     if (this != nullptr) {
  24.         ref_count_--;
  25.     }
  26. }
  27.  
  28. int shared_ptr::Storage::getCounter() const {
  29.     if (this == nullptr) {
  30.         return 0;
  31.     }
  32.     return ref_count_;
  33. }
  34.  
  35. Matrix* shared_ptr::Storage::getObject() const {
  36.     if (this == nullptr) {
  37.         return nullptr;
  38.     }
  39.     return data_;
  40. }
  41.  
  42. shared_ptr::shared_ptr(Matrix* obj) {
  43.     if (obj != NULL) {
  44.         storage_ = new Storage(obj);
  45.     } else {
  46.         storage_ = nullptr;
  47.     }
  48. }
  49.  
  50. shared_ptr::shared_ptr(const shared_ptr &other) {
  51.     *this = other;
  52. }
  53.  
  54. Matrix* shared_ptr::ptr() const {
  55.     if(this == 0) {
  56.         return nullptr;
  57.     }
  58.     return storage_->getObject();
  59. }
  60.  
  61. shared_ptr::~shared_ptr() {
  62.     storage_->decr();
  63.     if (storage_->getCounter() == 0){
  64.         delete storage_;
  65.     }
  66. }
  67.  
  68. void shared_ptr::reset(Matrix* obj) {
  69.     *this = shared_ptr(obj);
  70. }
  71.  
  72. bool shared_ptr::isNull() const {
  73.     return storage_== nullptr;
  74. }
  75.  
  76. shared_ptr& shared_ptr::operator=(const shared_ptr &other) {
  77.     storage_->decr();
  78.     if(storage_->getCounter() == 0) {
  79.         delete storage_;
  80.     }
  81.     storage_ = other.storage_;
  82.     storage_->incr();
  83.     return *this;
  84. }
  85.  
  86. Matrix* shared_ptr::operator->() const{
  87.     return storage_->getObject();
  88. }
  89.  
  90. Matrix& shared_ptr::operator*() const{
  91.     return *(storage_->getObject());
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement