C++智能指针
c++11的三个智能指针
unique_ptr独占指针,用的最多
shared_ptr记数指针,其次
weak_ptr,shared_ptr的补充,很少用
引用他们要加上头文件#include
unique_ptr独占指针:
1.只能有一个智能指针管理内存
2.当指针超出作用域时,内存将自动释放
3.不可copy,只能move
三种创建方式
前两种用的是拷贝构造函数,第三种用的是赋值构造函数。
1.通过已有裸指针创建
class Cat;
{
Cat(string name = “miaomiao”){}
void cat_infor(){}
}
Cat* cat = new Cat;
unique_ptr u_cat(cat);
cat = NULL;//为了防止通过cat改动,将其置空,更好的体现独占。
2.通过new创建,RAII,获得资源之时就是初始化之时
unique_ptr u_cat(new Cat);
3.通过sdt::make_unique创建(推荐)
unique_ptr u_cat = make_unique(“minmiao”);//make_unique是c++14中的
或
unique_ptr u_cat = make_unique(new Cat);
引用重载:
unique_ptr可以通过get()获取地址
unique_ptr实现了->调用成员函数
u_cat->cat_infor();
通过*调用dereferencing(解引用)
(*cat_infor).cat_infor();
移动:
move
do_with_cat_pass_value(unique u_cat){}
unique_ptr u_cat(new Cat);
do_with_cat_pass_value(move(u_cat));
那么此时就不能再使用
u_cat->cat_infor(),因为独占权已经不存在u_cat中了,其实make_unique()也是一种move。