共享指針
這個智能指針命名為boost::shared_ptr,定義在boost/shared_ptr.hpp里。智能指針boost::shared_ptr基本上類似於boost::scoped_ptr。關鍵不同之處在於boost::shared_ptr不一定要獨占一個對象。它可以和其他boost::shared_ptr類型的智能指針共享所有權。在這種情況下,當引用對象的最后一個智能指針銷毀后,對象才會被釋放。
因為所有權可以在boost::shared_ptr之間共享,任何一個共享指針都可以被復制,這跟boost::scoped_ptr是不同的。這樣就可以在標准容器里存儲智能指針了--你不能在標准容器中存儲std::auto_ptr,因為它們在拷貝的時候傳遞了所有權。
1 #include <iostream> 2 #include <algorithm> 3 #include <vector> 4 #include <boost/shared_ptr.hpp> 5 6 void show(boost::shared_ptr<int>p) 7 { 8 std::cout << *p << std::endl; 9 } 10 11 void main() 12 { 13 std::vector<boost::shared_ptr<int>>v; 14 15 boost::shared_ptr<int>p1(new int(11)); 16 boost::shared_ptr<int>p2(new int(12)); 17 boost::shared_ptr<int>p3(new int(13)); 18 19 v.push_back(p1); 20 v.push_back(p2); 21 v.push_back(p3); 22 23 for_each(v.begin(), v.end(), show); 24 }
使用boost::shared_ptr的類型初始化新對象,是淺拷貝
1 #include <iostream> 2 #include <boost/shared_ptr.hpp> 3 4 class runclass 5 { 6 public: 7 int i = 0; 8 public: 9 runclass(int num) :i(num) 10 { 11 std::cout << "i creator " << i << std::endl; 12 } 13 ~runclass() 14 { 15 std::cout << "i delete " << i << std::endl; 16 } 17 void print() 18 { 19 std::cout << "i=" << i << std::endl; 20 } 21 }; 22 23 void show(boost::shared_ptr<int>p) 24 { 25 std::cout << *p << std::endl; 26 } 27 28 void main() 29 { 30 boost::shared_ptr<runclass>p1(new runclass(10));//有調用構造函數 31 32 boost::shared_ptr<runclass>p2(p1);//淺拷貝,沒有調用構造函數 33 boost::shared_ptr<runclass>p3(p1);//淺拷貝,沒有調用構造函數 34 35 p1.reset(new runclass(12));//有調用構造函數 36 37 p1->print(); 38 p2->print(); 39 p3->print(); 40 }