shared_ptr是一個模板類,它保存了一個指向動態分配的對象的指針,當指向這個對象的最後一個shared_ptr被銷燬的時候,這個對象也被銷燬了。
有三種使用 shared_ptr的方法:
1)使用 std::shared_ptr
要用 std::shared_ptr的方式使用。
實例代碼:
#include <iostream> #include <memory> class A { public: A() { std::cout <<"A constructor" << std::endl; a = new int(3); } ~A() { std::cout <<"A destructor" << std::endl; delete a; a = NULL; } void Print(void) { std::cout << "a = " <<*a << std::endl; } private: int *a; }; void foo(std::shared_ptr<A> pA) { std::cout <<"user count : ##" << pA.use_count() << std::endl; std::shared_ptr <A> pB = pA; std::cout <<"user count : ###" << pA.use_count() << std::endl; pB.get()->Print(); } int main(void) { std::shared_ptr<A> p1 (new A); std::cout << "use count #" << p1.use_count() << std::endl; foo(p1); std::cout << "use count ####" << p1.use_count() << std::endl; return 0; }
編譯的時候,要加上 -std=c++11選項,因爲 shared_ptr是 c++11標準的一部分。
2)使用 tr1:shared_ptr
要用std:tr1::shared_ptr的方式使用
實例代碼:
#include <iostream> #include <tr1/memory> class A { public: A() { std::cout <<"A constructor" << std::endl; a = new int(3); } ~A() { std::cout <<"A destructor" << std::endl; delete a; a = NULL; } void Print(void) { std::cout << "a = " <<*a << std::endl; } private: int *a; }; void foo(std::tr1::shared_ptr<A> pA) { std::cout <<"user count : ##" << pA.use_count() << std::endl; std::tr1::shared_ptr <A> pB = pA; std::cout <<"user count : ###" << pA.use_count() << std::endl; pB.get()->Print(); } int main(void) { std::tr1::shared_ptr<A> p1 (new A); std::cout << "use count #" << p1.use_count() << std::endl; foo(p1); std::cout << "use count ####" << p1.use_count() << std::endl; return 0; }
這種情況下,直接用g++編譯就行了。
3)使用 boost庫。
要先確保已經安裝了 boost庫。在 ubuntu上,可以用下面的方法檢查:
$ dpkg --get-selections | grep boost libboost-date-time1.54.0:i386 install libboost-dev install libboost-iostreams1.54.0:i386 install libboost-system1.54.0:i386 install libboost1.54-dev install
要用 boost::shared_ptr的方式使用。
實例代碼:
#include <iostream> //#include <memory> #include <boost/tr1/tr1/memory> class A { public: A() { std::cout <<"A constructor" << std::endl; a = new int(3); } ~A() { std::cout <<"A destructor" << std::endl; delete a; a = NULL; } void Print(void) { std::cout << "a = " <<*a << std::endl; } private: int *a; }; void foo(boost::shared_ptr<A> pA) { std::cout <<"user count : ##" << pA.use_count() << std::endl; boost::shared_ptr <A> pB = pA; std::cout <<"user count : ###" << pA.use_count() << std::endl; pB.get()->Print(); } int main(void) { boost::shared_ptr<A> p1 (new A); std::cout << "use count #" << p1.use_count() << std::endl; foo(p1); std::cout << "use count ####" << p1.use_count() << std::endl; return 0; }
也可以直接用 g++編譯。
References:
1) http://stackoverflow.com/questions/2918202/where-is-shared-ptr
2)http://www.boost.org/doc/libs/1_58_0/libs/smart_ptr/shared_ptr.htm
时间: 2024-11-04 13:07:39