avr39ripe

cppWeak_ptrExample

Sep 28th, 2021
690
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. class Item
  5. {
  6.     std::string name;
  7.     std::weak_ptr<Item> pair;
  8. public:
  9.     const int size{ 34 };
  10.     Item(std::string nameP) : name{ nameP } { std::cout << "Item created for " << this << '\n'; }
  11.  
  12.     Item(const Item& it) = delete;
  13.     Item& operator=(const Item& it) = delete;
  14.  
  15.  
  16.     const std::string& getName()const { return name; };
  17.  
  18.     void print()const { std::cout << "Item # " << this << " named " << name << '\n'; }
  19.     ~Item() { std::cout << "Item destroyed for " << this << '\n'; }
  20.  
  21.     const std::shared_ptr<Item> getPair()const { return pair.lock(); }
  22.  
  23.     friend bool addPair(std::shared_ptr<Item>& left, std::shared_ptr<Item>& right)
  24.     {
  25.         if (!left or !right)
  26.         {
  27.             return false;
  28.         }
  29.  
  30.         left->pair = right;
  31.         right->pair = left;
  32.  
  33.         std::cout << left->getName() << " paired with " << right->getName() << '\n';
  34.  
  35.         return true;
  36.     }
  37.  
  38.     friend bool addFriend(std::shared_ptr<Item>& left, std::shared_ptr<Item>& right)
  39.     {
  40.         if (!left or !right)
  41.         {
  42.             return false;
  43.         }
  44.  
  45.         left->pair = right;
  46.        
  47.         std::cout << right->getName() << " is friend of " << left->getName() << '\n';
  48.  
  49.         return true;
  50.     }
  51. };
  52.  
  53. void printItem(Item* it)
  54. {
  55.     it->print();
  56. }
  57.  
  58.  
  59. int main()
  60. {
  61.     std::shared_ptr<Item> it1{ std::make_shared<Item>("Item One") };//[One - 1]
  62.     std::shared_ptr<Item> it2{ std::make_shared<Item>("Item Two") };//[Two - 1]
  63.    
  64.     addPair(it1, it2); // [One - 1] [Two - 1]
  65.     //addFriend(it1, it2);
  66.  
  67.     std::cout << std::boolalpha << "One paired with Two: " << (it1 == it2->getPair()) << '\n'; // [One - 2] [Two - 1] -> [One - 1] [Two - 1]
  68.     std::cout << std::boolalpha << "Two paired with One: " << (it2 == it1->getPair()) << '\n'; // [One - 1] [Two - 2] -> [One - 1] [Two - 1]
  69.  
  70.     auto it1Pair{ it1->getPair() }; //[Two - 2]
  71.     auto it2Pair{ it2->getPair() }; //[One - 2]
  72.  
  73.     std::cout << "Item One pair is: " << it1Pair->getName() << '\n';
  74.     std::cout << "Item two pair is: " << it2Pair->getName() << '\n';
  75.  
  76.     //it1->print();
  77.     //it2->print();
  78.  
  79.  
  80.     return 0;
  81. }
  82. // it2Pair - [One - 1]
  83. // it1Pair - [Two - 1]
  84. // it2 [Two - 0 x]
  85. // it1 [One - 0 x]
  86.  
  87.  
  88.  
  89.  
RAW Paste Data