unique

您所在的位置:网站首页 ss17导弹何时销毁 unique

unique

2023-08-15 23:16| 来源: 网络整理| 查看: 265

1.什么是uniqueptr

uniqueptr是智能指针的一种,主要用于C++的内存申请和释放,因为C++在申请内存后,要手动进行delete,这样就会出现有时候忘记delete,或者return,break,异常等原因没有执行到delete,如下面的代码所示,new了一个A的对象,要时刻注意delete销毁对象,而且如果是new了多个对象,需要同时注意什么时候销毁什么对象,return,break,异常等情况都要考虑,所以这就给开发造成很大的困扰。不知道什么时候delete内存,所以引入uniqueptr指针,当指针销毁不时,自动删除指针指向的内存。unique_ptr的特点是只允许一个指针指向这块内存,unique_ptr赋值操作是不允许的,例如uniqueptr1=uniqueptr2;是不允许的,只能通过转移,uniqueptr1=move(uniqueptr2);将uniqueptr2指向的内存转移给uniqueptr1。

#include #include using namespace std; class A {}; int main() { A* ptrA = new A; try {    if()    {        delete ptrA;      return -1;    }     //... //... //... //... //... } catch (...) { delete ptrA; //1 throw; } delete ptrA; //2 return 0; }

 

2.使用方法

上面的代码如果用uniqueptr就方便很多,只要申请unique_ptr指针指向内存,ptrA的作用域结束后销毁,会自动销毁ptrA 指向的内存;不用再去关注什么时候销毁内存;

#include #include using namespace std; class A {}; int main() { unique_ptr ptrA = make_unique();  //unique_ptr ptrA(new A);//第二种方式 try {     if()     {         //.....       return -1;     }      //... //... //... //... //... } catch (...) { throw; } return 0; }

3.详细介绍

#include "stdafx.h" #include using namespace std; #include #include int main() { unique_ptr uptr1 = make_unique();//新建第一个对象 //unique_ptr uptr2 = uptr1;//错误,唯一指向,不能赋值给其他指针 unique_ptr uptr2 = move(uptr1);//将指针uptr1指向的内存转移给uptr2,uptr1变为空 unique_ptr uptr3= make_unique();//新建第二个对象 int* p4 = uptr3.get();//返回指针uptr3指向的对象,可以修改对象的值,但是不能执行delete p4;否则uptr3销毁时释放内存会报错; *p4 = 8;//修改内存保存的值 //delete p4;//会报错如下图所示,这里销毁一次,uptr3又销毁一次; uptr3.release();//释放uptr3指向内存,但是不销毁内存; unique_ptr uptr4(new int);//新建第三个对象 uptr4.reset();//清空uptr4指向,并且销毁指向内存; unique_ptr uptr5(new int);//新建第四个对象; uptr5.reset(new int);//新建第五个对象,uptr5指向第五个对象,并销毁第四个对象内存; unique_ptr uptr6; uptr6.reset(new int);//新建第六个对象,uptr6指向第六个对象 return 0; }

 

 

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3