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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
| #include <stdlib.h> #include <iostream> #include <sstream> #include <string> #include <memory>
class Human { public: Human() : mNum(nullptr) { mNum = new int(123); printf("Human 构造\n"); } Human(const Human& _h) { mNum = new int(*_h.mNum); printf("Human 拷贝构造\n"); } Human(Human && _h) { mNum = _h.mNum; _h.mNum = nullptr; printf("Human 移动构造\n"); } virtual ~Human() { printf("Human 析构\n"); if (mNum) delete mNum; } void show(){ if(mNum) printf("--- num:%d\n", *mNum); } private: int* mNum; };
void testSmartPoint1() { std::unique_ptr<Human> up1(new Human); up1->show();
std::unique_ptr<Human> up3 = std::move(up1); up3->show();
up3.reset(); system("pause"); }
void testSmartPoint2() {
std::shared_ptr<Human> sp1(new Human()); std::shared_ptr<Human> sp2 = sp1; std::shared_ptr<Human> sp3 = sp1; printf("--- ref count:%ld\n", sp2.use_count());
sp1.reset(); sp1.reset(); sp1.reset(); printf("--- sp1 ref count:%ld\n", sp1.use_count());
printf("--- sp2 ref count:%ld\n", sp2.use_count()); printf("--- sp3 ref count:%ld\n", sp3.use_count());
sp2.reset(); printf("--- sp2 ref count:%ld\n", sp2.use_count()); printf("--- sp3 ref count:%ld\n", sp3.use_count());
sp3.reset(); printf("--- sp3 ref count:%ld\n", sp3.use_count()); system("pause"); }
void testSmartPoint3() { std::shared_ptr<Human> sp1(new Human()); std::shared_ptr<Human> sp2 = sp1; std::weak_ptr<Human> wp = sp1;
printf("--- ref count:%ld\n", sp2.use_count());
sp2.reset();
printf("--- sp1 count:%ld\n", sp1.use_count()); std::shared_ptr<Human> sp4 = wp.lock(); if (sp4) printf("--- sp4 ref count:%ld\n", sp4.use_count());
sp1.reset(); printf("--- wp ref count:%ld\n", wp.use_count()); if (sp4) sp4.reset(); printf("--- wp ref count:%ld\n", wp.use_count());
std::shared_ptr<Human> sp5 = wp.lock(); if (sp5) printf("--- sp5 ref count:%ld\n", sp4.use_count());
}
int main() { testSmartPoint3();
system("pause"); return 0; }
|