C++的智能指針

C和C++中都容許使用指針,使用指針就有一個致命的肯定,那就是內存釋放的問題,習慣了java寫法程序員,不適應指針那是固然,對內存的釋放也是雲裏霧裏。爲了減小程序開發的困擾,在C++中引入了智能指針的功能,所謂智能指針即程序員能夠不用關心內存的釋放問題,程序會根據當前的引用狀況自動釋放內存。java

在C++中智能指針包括四種類型:auto_ptr, shared_ptr, weak_ptr, unique_ptr程序員

auto_ptr是C++98中實現的,而其餘後三種是在C++11中實現的。指針

 

auto_ptr的使用內存

auto_ptr<string> ps = auto_ptr<string>(new string("test"));開發

此時new出來的string不須要主動釋放,當使用完成以後智能指針會主動釋放。string

那auto_ptr有什麼缺陷呢?編譯

看下面的例子:test

string str = new string("hello");變量

auto_ptr<string> ps1 = auto_ptr<string>(str);引用

auto_ptr<string> ps2 = auto_ptr<string>(str);

按照上面的說法智能指針會主動釋放指針,那這樣的話str這個變量不是會被釋放兩次嗎,這樣就會出現一個重複釋放的問題,爲了解決這個問題就引入shared_ptr和unique_ptr

 

unique_ptr的使用

unique_ptr會把可能的錯誤暴露在編譯時,那麼上面這段代碼改爲下面的代碼就會出現錯誤:

 

string str = new string("hello");

unique_ptr<string> ps1 = unique_ptr<string>(str);

unique_ptr<string> ps2 = unique_ptr<string>(str);

 

unique_ptr只容許一個智能指針指向這段內存,那若是我須要多個指向怎麼辦呢?這個時候能夠使用shared_ptr

 

share_ptr的使用

string str = new string("hello");

shared_ptr<string> ps1 = shared_ptr<string>(str);

shared_ptr<string> ps2 = ps1;

這樣是能夠的,shared_ptr採用計數的方式,當進行一次賦值則引用計數加1,當釋放的使用引用計數減1.

相關文章
相關標籤/搜索