日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

c++智能指針unique_ptr的使用_C 語言

作者:鶸鶸19960712 ? 更新時間: 2022-03-17 編程語言

1.為什么需要unique_ptr

與shared_ptr作用類似,需要解決內(nèi)存泄漏的問題,但是卻不需要使用shared_ptr的引用計數(shù),所以為了減少消耗,就需要一個這樣的智能指針。但是使用已被廢棄的auto_ptr的話就會有新的問題,auto_ptr在使用過程中如果被拷貝構(gòu)造或者賦值的話,被復(fù)制的auto_ptr就失去了作用,這個時候就需要在auto_ptr的基礎(chǔ)上禁用拷貝構(gòu)造以及賦值操作,也就成了unique_ptr。

2.什么是unique_ptr

一個unique_ptr獨享它指向的對象。也就是說,同時只有一個unique_ptr指向同一個對象,當(dāng)這個unique_ptr被銷毀時,指向的對象也隨即被銷毀。使用unique_ptr需要引入<memory.h>

3.unique_ptr特性

unique_ptr禁用了拷貝構(gòu)造以及賦值操作,也就導(dǎo)致了下面的這些操作無法完成。

void testFunction(std::unique_ptr<Test> t){
    t->getString();
}

void features(){
    // Disable copy from lvalue.
    //    unique_ptr(const unique_ptr&) = delete;
    //    unique_ptr& operator=(const unique_ptr&) = delete;
    //不能進行拷貝構(gòu)造以及賦值運算,也就表示不能作為函數(shù)參數(shù)傳遞
     std::unique_ptr<Test> t(new Test);
     std::unique_ptr<Test> t2 = t; //編譯報錯
     std::unique_ptr<Test> t3(t);//編譯報錯
     testFunction(t);//編譯報錯
}

4.如何使用unique_ptr

4.1簡單使用

void simpleUse(){
    Test *test = new Test;
    std::unique_ptr<Test> t(test);
     qDebug() << test  <<"獲取原始指針"<< t.get() <<endl;
     
    //    t.release(); //釋放其關(guān)聯(lián)的原始指針的所有權(quán),并返回原始指針,沒有釋放對象
    //    t.reset();// 釋放對象
    t->getString();

    std::unique_ptr<Test> t2 = std::move(t); //交換使用權(quán)到t2;
    t2->getString();
}

運行結(jié)果

4.2指向數(shù)組

和shared_ptr需要注意的地方一樣,指向數(shù)組時要注意模板書寫的方式,以及如何使用自定義刪除器

錯誤寫法:會導(dǎo)致內(nèi)存泄露

void customRemover(){
    std::unique_ptr<Test> t(new Test[5]);
}

錯誤方法輸出

正確寫法:

void customRemover(){
    std::unique_ptr<Test[]> t(new Test[5]);
    
    std::unique_ptr<Test, void(*)(Test *)> p2(new Test[5],[](Test *t){
        delete []t;
    });
}

5.unique_ptr需要注意什么

不要多個unique_ptr指向同一個對象
例如:

void repeatPointsTo(){
    Test *test = new Test;
    std::unique_ptr<Test> t(test);
    std::unique_ptr<Test> t2(test);
    //兩個unique_ptrzhi'xi指向同一個對象,會導(dǎo)致這個對象被析構(gòu)兩次,導(dǎo)致問題出現(xiàn)
}

運行結(jié)果

會導(dǎo)致對象會被多次析構(gòu),導(dǎo)致崩潰

原文鏈接:https://blog.csdn.net/aaaaaacc7/article/details/122149762

欄目分類
最近更新