北京大兴行业网站建设公司,灵芝产品网站建设方案,建设网站如何挣钱,wordpress简单投稿c11的三个智能指针 unique_ptr独占指针#xff0c;用的最多 shared_ptr记数指针#xff0c;其次 weak_ptr#xff0c;shared_ptr的补充#xff0c;很少用 引用他们要加上头文件#include
unique_ptr独占指针#xff1a; 1.只能有一个智能指针管理内存 2.当指针超出作用域…c11的三个智能指针 unique_ptr独占指针用的最多 shared_ptr记数指针其次 weak_ptrshared_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是c14中的 或 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。