首页 > 编程语言 > 详细

C++11 智能指针

时间:2020-01-31 23:10:57      阅读:80      评论:0      收藏:0      [点我收藏+]

【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.

顺序 选择 循环 总结

C++11 智能指针

原文:https://www.cnblogs.com/Braveliu/p/12247042.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!