C++智能指標shared_ptr

來源:互聯網
上載者:User

標籤:soft   main   使用   baidu   ash   syn   意思   對象   class   

shared_ptr這裡有一個你在標準庫中找不到的—引用數智能指標。大部分人都應當有過使用智能指標的經曆,並且已經有很多關於引用數的文章。最重要的一個細節是引用數是如何被執行的—插入,意思是說你將引用計數的功能添加給類,或者是非插入,意思是說你不這樣做。Boost shared_ptr是非插入類型的,這個實現使用一個從堆中分配來的引用計數器。關於提供參數化策略使得對任何情況都極為適合的討論很多了,但是最終討論的結果是決定反對聚焦於可用性。可是不要指望討論的結果能夠結束。shared_ptr完成了你所希望的工作:他負責在不使用執行個體時刪除由它指向的對象(pointee),並且它可以自由的共用它指向的對象(pointee)。
123456789101112131415161718192021222324252627282930 void PrintIfString?(constany&Any){if(cons tshared_ptr* s=any_cast>(&Any)){cout<<**s<<endl;}}int main(int argc,char* argv[]){std::vectorStuff;shared_ptrSharedString1?(new string("Shareme.Bytheway,Boost.anyisanotherusefulBoostlibrary"));shared_ptrSharedString2?(SharedString1?);shared_ptrSharedInt1?(newint(42));shared_ptrSharedInt2?(SharedInt1?);Stuff.push_back(SharedString1?);Stuff.push_back(SharedString2?);Stuff.push_back(SharedInt1?);Stuff.push_back(SharedInt2?);//Printthestringsfor_each(Stuff.begin(),Stuff.end(),PrintIfString?);Stuff.clear();//Thepointeesoftheshared_ptr‘s//willbereleasedonleavingscope//shared_ptr的pointee離開這個範圍後將被釋放return0;}

什麼叫智能指標?智能指標介紹。

智能指標(smart pointer)是儲存指向動態分配(堆)對象指標的類,用於生存期控制,能夠確保自動正確的銷毀動態分配的對象,防止記憶體泄露。它的一種通用實現技術是使用引用..

C++智能指標shared_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.