std::unique_ptr:智能指针
场景:
当你需要使用指针来管理你的资源时
方法:
get:访问对象
reset:重置对象。会调用delete
release:释放对象,不会调用delete
例子
#include <iostream>
#include <memory>
using namespace std;
int main()
{
//创建一个unique_ptr
unique_ptr<int> p(new int(5));
//访问该对象
cout<<*p<<endl;
cout<<*p.get()<<endl;
//通过move创建
auto p1 = std::move(p);
cout<<*p1<<endl;
//直接和nullptr比较是否为空,move后unique_ptr为空
if(nullptr == p){
cout<<"p == nullptr"<<endl;
}
if(nullptr != p1){
cout << "p1 != nullptr" << endl;
}
//重置unique_ptr为空,delete其关联的指针
// p1.reset();
//通过release来不delete关联指针,并返回关联指针。释放关联指针的所有权,unique_ptr为空
int* val = p1.release();
cout << "val:" << *val << endl;
//被relase后应该手动来删除,否则会存在泄露
delete val;
return 0;
}
运行结果
5
5
5
p == nullptr
p1 != nullptr
val:5
使用扩展
管理动态数组
//管理动态数组
std::unique_ptr<int[]> arr(new int[5]{1,2,3,4,5});
for(int i = 0;i < 5;i++){
cout << arr[i] << " ";
}
cout <<endl;
结果
1 2 3 4 5
做为函数返回值
std::unique_ptr<int> fun1()
{
return std::unique_ptr<int>(new int(10086));
}
//获取函数返回值
auto ret = fun1();
cout << *ret << endl;
结果
10086
在容器中使用
std::vector< std::unique_ptr<int> > vec;
for(int i = 0;i < 10;i++){
std::unique_ptr<int> var(new int(i));
vec.push_back(std::move(var));
}
for(size_t i = 0;i < vec.size();i++){
std::cout << *( vec.at(i) )<< " ";
}
std::cout << endl;
结果
0 1 2 3 4 5 6 7 8 9