c++11 智能指標 unique_ptr、shared_ptr與weak_ptr

來源:互聯網
上載者:User

標籤:check   實現   操作符   mem   使用   class   end   另一個   顯示   

c++11 智能指標 unique_ptr、shared_ptr與weak_ptr

 

C++11中有unique_ptr、shared_ptr與weak_ptr等智能指標(smart pointer),定義在<memory>中。

可以對動態資源進行管理,保證任何情況下,已構造的對象最終會銷毀,即它的解構函式最終會被調用。

 

unique_ptr

unique_ptr持有對對象的專屬權,同一時刻只能有一個unique_ptr指向給定對象(通過禁止拷貝語義、只有移動語意來實現)。

unique_ptr指標本身的生命週期:從unique_ptr指標建立時開始,直到離開範圍。

離開範圍時,若其指向對象,則將其所指對象銷毀(預設使用delete操作符,使用者可指定其他動作)。

 

#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <string>#include <memory>#include <vector>#include <map>void mytest(){    std::unique_ptr<int> up1(new int(11));   // 無法複製的unique_ptr    //unique_ptr<int> up2 = up1;        // err, 不能通過編譯    std::cout << *up1 << std::endl;   // 11    std::unique_ptr<int> up3 = std::move(up1);    // 現在p3是資料的唯一的unique_ptr    std::cout << *up3 << std::endl;   // 11    //std::cout << *up1 << std::endl;   // err, 執行階段錯誤    up3.reset();            // 顯式釋放記憶體    up1.reset();            // 不會導致執行階段錯誤    //std::cout << *up3 << std::endl;   // err, 執行階段錯誤    std::unique_ptr<int> up4(new int(22));   // 無法複製的unique_ptr    up4.reset(new int(44)); //"綁定"動態對象    std::cout << *up4 << std::endl; // 44    up4 = nullptr;//顯式銷毀所指對象,同時智能指標變為空白指標。與up4.reset()等價    std::unique_ptr<int> up5(new int(55));    int *p = up5.release(); //只是釋放控制權,不會釋放記憶體    std::cout << *p << std::endl;    //cout << *up5 << endl; // err, 執行階段錯誤    delete p; //釋放堆區資源    return;}int main(){    mytest();    system("pause");    return 0;}

 

shared_ptr

shared_ptr允許多個該智能指標共用第“擁有”同一堆指派至的記憶體,這通過引用計數(reference counting)實現,會記錄有多少個shared_ptr共同指向一個對象,一旦最後一個這樣的指標被銷毀,也就是一旦某個對象的引用計數變為0,這個對象會被自動刪除。

 

#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <string>#include <memory>#include <vector>#include <map>void mytest(){    std::shared_ptr<int> sp1(new int(22));    std::shared_ptr<int> sp2 = sp1;    std::cout << "cout: " << sp2.use_count() << std::endl; // 列印引用計數    std::cout << *sp1 << std::endl;    std::cout << *sp2 << std::endl;    sp1.reset(); // 顯示讓引用計數減一    std::cout << "count: " << sp2.use_count() << std::endl; // 列印引用計數    std::cout << *sp2 << std::endl; // 22    return;}int main(){    mytest();    system("pause");    return 0;}

 

weak_ptr

weak_ptr是為配合shared_ptr而引入的一種智能指標來協助shared_ptr工作,它可以從一個shared_ptr或另一個weak_ptr物件建構,它的構造和析構不會引起引用計數的增加或減少。沒有重載 * 和 -> 但可以使用lock獲得一個可用的shared_ptr對象

weak_ptr的使用更為複雜一點,它可以指向shared_ptr指標指向的對象記憶體,卻並不擁有該記憶體,而使用weak_ptr成員lock,則可返回其指向記憶體的一個share_ptr對象,且在所指對象記憶體已經無效時,返回指標空值nullptr。

注意:weak_ptr並不擁有資源的所有權,所以不能直接使用資源。
可以從一個weak_ptr構造一個shared_ptr以取得共用資源的所有權。

 

#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <string>#include <memory>#include <vector>#include <map>void check(std::weak_ptr<int> &wp){    std::shared_ptr<int> sp = wp.lock(); // 轉換為shared_ptr<int>    if (sp != nullptr)    {        std::cout << "still: " << *sp << std::endl;    }     else    {        std::cout << "still: " << "pointer is invalid" << std::endl;    }}void mytest(){    std::shared_ptr<int> sp1(new int(22));    std::shared_ptr<int> sp2 = sp1;    std::weak_ptr<int> wp = sp1; // 指向shared_ptr<int>所指對象    std::cout << "count: " << wp.use_count() << std::endl; // count: 2    std::cout << *sp1 << std::endl; // 22    std::cout << *sp2 << std::endl; // 22    check(wp); // still: 22        sp1.reset();    std::cout << "count: " << wp.use_count() << std::endl; // count: 1    std::cout << *sp2 << std::endl; // 22    check(wp); // still: 22    sp2.reset();    std::cout << "count: " << wp.use_count() << std::endl; // count: 0    check(wp); // still: pointer is invalid    return;}int main(){    mytest();    system("pause");    return 0;}

 

c++11 智能指標 unique_ptr、shared_ptr與weak_ptr

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.