C++ std::tr1::shared_ptr使用

來源:互聯網
上載者:User

看《effective c++》,作者一直強調用std::tr1::shared_ptr,比起auto_ptr好多了。

shared_ptr採用引用計數,多個指標可以指向同一個對象;auto_ptr就不能,只能運行一個指標指向一個對象:如果要指標賦值,那麼原來的指標要放棄對該對象的所有權。

恩,以後都用shared_ptr。

shared_ptr在最新的c++11中,已經被列入了標準指標,而auto_ptr則出局了。

說了那麼多,shared_ptr採用RAII技術,是防止記憶體泄露的神器。

按bnu_chenshuo的說法,他最後一次看見代碼中的記憶體泄露還是04年他做實習生的時候。

而C++沉思錄的作者AndrewKoenig也極力推薦使用標準庫,不用指標。

看下面的程式,我new了一個對象,並沒有在程式中使用delete,但是,運行程式,其建構函式仍然運行!這就是shared_ptr,如果要預防記憶體泄露,它就是最佳選擇!

 1 # include <iostream>
2 # include <tr1/memory>
3 using namespace std;
4 class A {
5 public:
6 A() {
7 cout << "construct A!!!" << endl;
8 }
9 ;
10 ~A() {
11 cout << "destruct A!!!" << endl;
12 }
13 ;
14 };
15 class B: public A {
16 public:
17 B() {
18 cout << "construct B!!!" << endl;
19 }
20 ;
21 ~B() {
22 cout << "destruct B!!!" << endl;
23 }
24 ;
25 };
26 int main() {
27 // B* ptrB0 = new B();
28 std::tr1::shared_ptr<B> ptrB1(new B);
29 }

運行結果:

 

construct A!!!
construct B!!!
destruct B!!!
destruct A!!!

轉自:http://blog.csdn.net/randyjiawenjie/article/details/6710066

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.