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
原创粉丝点击