Ledger Nano X - The secure hardware wallet
SHARE
TWEET

SharedPointer by Marek Padlewski

a guest Apr 7th, 2020 135 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. template <typename T>
  5. class MySharedPointer{
  6. public:
  7.     explicit MySharedPointer(T* pointer = nullptr){
  8.         counter = new unsigned int(0);
  9.         my_ptr = pointer;
  10.         if (pointer)
  11.             (*counter)++;
  12.     }
  13.  
  14.     MySharedPointer(MySharedPointer<T>& other_sptr){
  15.         counter = other_sptr.counter;
  16.         my_ptr = other_sptr.my_ptr;
  17.         if (other_sptr.my_ptr)
  18.             (*counter)++; //increase counter in all instances
  19.     }
  20.  
  21.     MySharedPointer<T>& operator=(const MySharedPointer<T>& other_sptr){
  22.  
  23.         if (this != &other_sptr){
  24.             counter = other_sptr.counter;
  25.             my_ptr = other_sptr.my_ptr;
  26.             if (other_sptr.my_ptr)
  27.                 (*counter)++;
  28.         }
  29.  
  30.         return *this;
  31.     }
  32.  
  33.     ~MySharedPointer(){
  34.         if (*counter == 0){
  35.             delete my_ptr;
  36.             delete counter;
  37.         }
  38.         else
  39.             (*counter)--;
  40.     }
  41.  
  42.     unsigned int getCount(){
  43.         return *counter;
  44.     }
  45.  
  46. private:
  47.     unsigned int* counter;
  48.     T* my_ptr;
  49. };
  50.  
  51.  
  52. int main() {
  53.  
  54.     MySharedPointer<int> msp(new int(42));
  55.     std::cout << msp.getCount() << std::endl;
  56.  
  57.     {
  58.         MySharedPointer<int> msp2;
  59.         msp2 = msp;
  60.         std::cout << msp2.getCount() << std::endl;
  61.  
  62.         msp2 = MySharedPointer<int>(new int(17));
  63.         std::cout << msp2.getCount() << std::endl;
  64.         std::cout << msp.getCount() << std::endl;
  65.  
  66.     }
  67.  
  68.     std::cout << msp.getCount() << std::endl;
  69.  
  70.     return 0;
  71. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top