C++30、智能指针
来源:互联网 发布:imovie windows版下载 编辑:程序博客网 时间:2024/05/22 00:15
之前C++中含有智能指针auto_ptr,但却在实践中不被推荐使用。现在C++11中,把boost库中的智能指针引入标准,使得如今的智能指针使用起来方便了许多。下面是两个简单的示例:
一、unique_ptr和shared_ptr
#include <memory>#include <iostream>using namespace std;int main(){unique_ptr<int> up1(new int(11));cout << *up1 << endl; unique_ptr<int>up3 = move(up1);cout << *up3 <<endl;up3.reset();up1.reset();shared_ptr<int> sp1(new int(22));shared_ptr<int> sp2 = sp1;cout << *sp1<<endl;cout << *sp2<<endl;sp1.reset();cout << *sp2 <<endl;//解除绑定,不再指向确定的内存单元//cout << *sp1 <<endl;return 0;}
二、weak_ptr
#include <memory>#include <iostream>using namespace std;void check(weak_ptr<int> &wp){shared_ptr<int> sp = wp.lock();if(sp !=nullptr){cout << "still" << *sp<<endl; }else{cout << "ptr is invalid" <<endl; }}int main(){shared_ptr<int> sp1(new int(22));shared_ptr<int> sp2 =sp1;//指向 shared_ptr<int>所指对象weak_ptr<int> wp = sp1;cout << *sp1<< endl;cout << *sp2<< endl;check(wp);sp1.reset();check(wp);sp2.reset();check(wp);//检查是否支持最小垃圾回收pointer_safety ps= get_pointer_safety();return 0;}
注:所使用代码来自《深入理解C++11》。
0 0
- c++:智能指针
- C++:智能指针
- 【C++】智能指针
- 【C++】智能指针
- C++PJ智能指针
- 【c++】智能指针
- 【C++】智能指针auto_ptr
- C++,智能指针
- C++,boost智能指针
- 智能指针模拟C
- [C++]智能指针
- 【C++】 浅析智能指针
- C++_智能指针
- C++:初识智能指针
- C++::智能指针
- 【C++】智能指针
- c智能指针:unique_ptr
- 【C++】智能指针
- gdb不知为何显示2次析构
- PHP 中文无乱码截取
- 使对象可以像数组一样进行foreach循环,要求属性必须是私有
- Vue2+VueRouter2+webpack 构建项目实战(三)配置路由,整俩页面先
- pdo类的简要说明
- C++30、智能指针
- Docker---从Docker复制文件到主机
- The Linux Programming Interface 02 Fundamental Concepts 基本概念
- Apache Maven 入门篇 ( 上 )
- 【HPU 1265 Triangles】+ 几何
- 一步一步在Windows中使用MyCat负载均衡 上篇
- 在Android项目中新建一个Activity
- Jmeter:几项重要测试指标含义
- Java中断点下载使用类RandomAccessFile