C++11 智能指针

社会主义新天地 提交于 2020-01-31 23:14:43

【1】C++11智能指针

应用示例如下:

 1 #include <iostream>
 2 #include <memory>
 3 using namespace std;
 4 
 5 void test_unique_ptr()
 6 {
 7     unique_ptr<int> up1(new int(2020));  // 无法复制的unique_ptr
 8 //    unique_ptr<int> up2 = up1;           // 不能通过编译
 9     cout << (*up1) << endl;              // 2020
10     unique_ptr<int> up3 = move(up1);     // 现在up3是数据唯一的unique_ptr智能指针
11     cout << (*up3) << endl;              // 2020
12 //    cout << (*up1) << endl;              // 运行时错误
13     up3.reset();                         // 显式释放内存
14     up1.reset();                         // 不会导致运行时错误
15 //    cout << (*up3) << endl;              // 运行时错误
16 }
17 
18 void test_shared_ptr()
19 {
20     shared_ptr<int> sp1(new int(131));
21     shared_ptr<int> sp2 = sp1;
22     cout << (*sp1) << endl;  // 131
23     cout << (*sp2) << endl;  // 131
24     sp1.reset();
25 //    cout << (*sp1) << endl;
26     cout << (*sp2) << endl;  // 131
27 }
28 
29 void check(weak_ptr<int> & wp)
30 {
31     shared_ptr<int> sp = wp.lock(); // 转换为shared_ptr
32     if (sp != nullptr)
33     {
34         cout << "still " << (*sp) << endl;
35     }
36     else
37     {
38         cout << "pointer is invalid." << endl;
39     }
40 
41 }
42 void test_weak_ptr()
43 {
44     shared_ptr<int> sp1(new int(2020));
45     shared_ptr<int> sp2 = sp1;
46     weak_ptr<int> wp = sp1;  // 指向shared_ptr<int>所指对象
47     cout << (*sp1) << endl;  // 2020
48     cout << (*sp2) << endl;  // 2020
49 
50     check(wp);               // still 2020
51     sp1.reset();
52     cout << (*sp2) << endl;  // 2020
53     check(wp);               // still 2020
54     sp2.reset();
55     check(wp);               // pointer is invalid
56 }
57 
58 int main()
59 {
60     test_unique_ptr();
61     test_shared_ptr();
62     test_weak_ptr();
63 }

 

good good study, day day up.

顺序 选择 循环 总结

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!