Example code
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
// Author: Huahua #include <iostream> #include <memory> class Entity { public: Entity() { puts("Entity created!"); } ~Entity() { puts("Entity destroyed!"); } }; void ex1() { puts("--------"); puts("Entering ex1"); { puts("Entering ex1::scope1"); auto e1 = std::make_unique<Entity>(); puts("Leaving ex1::scope1"); } puts("Leaving ex1"); } void foo(std::unique_ptr<Entity>) { puts("Entering foo"); puts("Leaving foo"); } void ex2() { puts("--------"); puts("Entering ex2"); auto e1 = std::make_unique<Entity>(); foo(std::move(e1)); // e1 was destoried. puts("Leaving ex2"); } void ex3() { puts("--------"); puts("Entering ex3"); auto e1 = std::make_shared<Entity>(); std::cout << e1.use_count() << std::endl; { puts("Entering ex3::scope1"); auto e2 = e1; // use_count ++ std::cout << e1.use_count() << std::endl; auto e3 = std::move(e2); // use_count remains std::cout << e1.use_count() << std::endl; puts("Leaving ex3::scope1"); } std::cout << e1.use_count() << std::endl; puts("Leaving ex3"); } void observe(std::weak_ptr<Entity> ew) { if (std::shared_ptr<Entity> spt = ew.lock()) { std::cout << spt.use_count() << std::endl; std::cout << "entity still alive!" << std::endl; } else { std::cout << "entity was expired :(" << std::endl; } } void ex4() { puts("--------"); puts("Entering ex4"); std::weak_ptr<Entity> ew; { puts("Entering ex4::scope1"); auto e1 = std::make_shared<Entity>(); std::cout << e1.use_count() << std::endl; ew = e1; // use_count remains std::cout << e1.use_count() << std::endl; observe(ew); puts("Leaving ex4::scope1"); } observe(ew); puts("Leaving ex4"); } int main(int argc, char** argv) { ex1(); ex2(); ex3(); ex4(); return 0; } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
-------- Entering ex1 Entering ex1::scope1 Entity created! Leaving ex1::scope1 Entity destroyed! Leaving ex1 -------- Entering ex2 Entity created! Entering foo Leaving foo Entity destroyed! Leaving ex2 -------- Entering ex3 Entity created! 1 Entering ex3::scope1 2 2 Leaving ex3::scope1 1 Leaving ex3 Entity destroyed! -------- Entering ex4 Entering ex4::scope1 Entity created! 1 1 2 entity still alive! Leaving ex4::scope1 Entity destroyed! entity was expired :( Leaving ex4 |