| 8 | } |
| 9 | |
| 10 | int main() |
| 11 | { |
| 12 | // auto pointer = new int(10); // illegal, no direct assignment |
| 13 | // Constructed a shared_ptr |
| 14 | auto pointer = make_shared<int>(10); |
| 15 | |
| 16 | foo(pointer); |
| 17 | |
| 18 | cout << *pointer << endl; // 11 |
| 19 | // The shared_ptr will be destructed before leaving the scope |
| 20 | |
| 21 | |
| 22 | auto pointer1 = make_shared<int>(10); |
| 23 | auto pointer2 = pointer1; // 引用计数 +1 |
| 24 | auto pointer3 = pointer1; // 引用计数 +1 |
| 25 | int *p = pointer1.get(); // 这样不会增加引用计数 |
| 26 | |
| 27 | cout << *p << endl; |
| 28 | cout << "pointer1.use_count() = " << pointer1.use_count() << endl; // 3 |
| 29 | cout << "pointer2.use_count() = " << pointer2.use_count() << endl; // 3 |
| 30 | cout << "pointer3.use_count() = " << pointer3.use_count() << endl; // 3 |
| 31 | |
| 32 | pointer2.reset(); |
| 33 | cout << "reset pointer2:" << endl; |
| 34 | cout << "pointer1.use_count() = " << pointer1.use_count() << endl; // 2 |
| 35 | cout << "pointer2.use_count() = " << pointer2.use_count() << endl; // 0, pointer2 已 reset |
| 36 | cout << "pointer3.use_count() = " << pointer3.use_count() << endl; // 2 |
| 37 | |
| 38 | pointer3.reset(); |
| 39 | cout << "reset pointer3:" << endl; |
| 40 | cout << "pointer1.use_count() = " << pointer1.use_count() << endl; // 1 |
| 41 | cout << "pointer2.use_count() = " << pointer2.use_count() << endl; // 0 |
| 42 | cout << "pointer3.use_count() = " << pointer3.use_count() << endl; // 0, pointer3 已 reset |
| 43 | |
| 44 | return 0; |
| 45 | } |
| 46 | |