Advertisement
cepxuozab

CasheLifeTime

Sep 28th, 2024
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. using namespace std;
  2. struct ObjectFactory2 {
  3.    
  4.     int count = 0;
  5.  
  6.     ObjectFactory2(int count) : count(count) {
  7.     }
  8.  
  9.     ObjectFactory2() = default;
  10.  
  11.     ObjectPtr operator()(std::string id) {
  12.         id += "_"s + to_string(count);
  13.         ++count;
  14.         return std::make_shared<Object>(std::move(id));
  15.     }
  16. };
  17. void CacheTest() {
  18.     using namespace std;
  19.     weak_ptr<Object> bob_wp;
  20.     {
  21.         Cache<string, Object, ObjectFactory2> cache;
  22.  
  23.         auto alice1 = cache.GetValue("Alice"s);
  24.         auto bob = cache.GetValue("Bob"s);
  25.  
  26.         auto alice2 = cache.GetValue("Alice"s);
  27.         assert(alice1== alice2);
  28.  
  29.         weak_ptr alice_wp{ alice1 };
  30.         bob_wp = bob;
  31.         assert(!alice_wp.expired());
  32.         assert(!bob_wp.expired());
  33.  
  34.         alice1.reset();
  35.         assert(!alice_wp.expired());
  36.  
  37.         alice2.reset();
  38.         assert(alice_wp.expired());
  39.     }
  40.     assert(bob_wp.expired());
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement