unique_ptr使用詳解(介紹,場景,方法,實例)

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 <memory>
#include<iostream>
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 <memory>
#include<iostream>
using namespace std;

class A {};
int main()
{
    unique_ptr<A> ptrA = make_unique<A>();
  //unique_ptr<A> ptrA(new A);//第二種方式
try {     if()     {         //.....       return -1;     }      //... //... //... //... //... } catch (...) { throw; } return 0; }

3.詳細介紹

#include "stdafx.h"

#include <iostream>
using namespace std;
#include <string>
#include <memory>

int main()
{
    
        unique_ptr<int> uptr1 = make_unique<int>();//新建第一個對象
        //unique_ptr<int> uptr2 = uptr1;//錯誤,唯一指向,不能賦值給其他指針
        unique_ptr<int> uptr2 = move(uptr1);//將指針uptr1指向的內存轉移給uptr2,uptr1變爲空
        unique_ptr<int> uptr3= make_unique<int>();//新建第二個對象
        int* p4 = uptr3.get();//返回指針uptr3指向的對象,可以修改對象的值,但是不能執行delete p4;否則uptr3銷燬時釋放內存會報錯;
        *p4 = 8;//修改內存保存的值
        //delete p4;//會報錯如下圖所示,這裏銷燬一次,uptr3又銷燬一次;
        uptr3.release();//釋放uptr3指向內存,但是不銷燬內存;
        unique_ptr<int> uptr4(new int);//新建第三個對象
        uptr4.reset();//清空uptr4指向,並且銷燬指向內存;
        unique_ptr<int> uptr5(new int);//新建第四個對象;
        uptr5.reset(new int);//新建第五個對象,uptr5指向第五個對象,並銷燬第四個對象內存;
        unique_ptr<int> uptr6;
        uptr6.reset(new int);//新建第六個對象,uptr6指向第六個對象
return 0; }

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章