標籤: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