(原)C++智能指標——釋放器(in linux, g++)

來源:互聯網
上載者:User

我的記錄:

1.指定了釋放器,就不會去直接調用解構函式。因為釋放器就一個。不指定的話解構函式就是釋放器.

2.STL智能指標對內建內型的支援不如class:比如shared_ptr<char> s(new char[10]); memset(s, 0x00, 10);//error! 只能memset(s.get(), ....了。

3. auto_ptr不能指定釋放器.

#include "iostream"#include <tr1/memory>using namespace std;using std::tr1::shared_ptr;using std::auto_ptr;class C{public:C(){ cout<<"C()"<<endl;  buf = new char[10];}~C(){ cout<<"~C()"<<endl;  if(buf){cout<<"~C() delete []buf."<<endl; delete [] buf;}}static void MyRelease(C * pC){cout<<"MyRelease()"<<endl;cout<<"MyRelease() delete [] buf."<<endl;delete [] pC->buf;pC->buf = NULL;cout<<"MyRelease() delete C:";delete pC;//call ~C().} private:char * buf;};int main(){cout<<"std::tr1::shared_ptr<C>:"<<endl;{C * a = new C;shared_ptr<C> shareC(a, C::MyRelease); }cout<<"<- shared_ptr test ended.\n"<<endl;cout<<"std::tr1::shared_ptr<C> copy test"<<endl;{shared_ptr<C> shareC(new C, C::MyRelease);shared_ptr<C> shareC2 = shareC;}cout<<"<- shared_ptr copy test ended.\n"<<endl;cout<<"std::auto_ptr<C>:"<<endl;C * b = new C;auto_ptr<C> autoC(b);cout<<"return 0;"<<endl;return 0;}

 
$ g++ main.cpp

相關文章

聯繫我們

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