一、boost::scoped_ptr是一个比较简单的智能指针,它能保证在离开做用域以后它所管理对象能被自动释放ios
1 #include <iostream> 2 #include <boost/scoped_ptr.hpp> 3 4 using namespace std; 5 6 class Book 7 { 8 public: 9 Book() 10 { 11 cout << "Creating book ..." << endl; 12 } 13 14 ~Book() 15 { 16 cout << "Destroying book ..." << endl; 17 } 18 }; 19 20 int main() 21 { 22 cout << "=====Main Begin=====" << endl; 23 { 24 boost::scoped_ptr<Book> myBook(new Book()); 25 } 26 cout << "===== Main End =====" << endl; 27 28 return 0; 29 }
二、 boost::shared_ptr是能够共享全部权的指针。若是有多个shared_ptr共同管理同一个对象时,只有这些shared_ptr所有与该对象脱离关系以后,被管理的对象才会被释放。经过下面这个例子先了解下shared_ptr的基本用法:。函数
1 #include <iostream> 2 #include <string> 3 #include <boost/shared_ptr.hpp> 4 5 using namespace std; 6 7 class Book 8 { 9 private: 10 string name_; 11 12 public: 13 Book(string name) : name_(name) 14 { 15 cout << "Creating book " << name_ << " ..." << endl; 16 } 17 18 ~Book() 19 { 20 cout << "Destroying book " << name_ << " ..." << endl; 21 } 22 }; 23 24 int main() 25 { 26 cout << "=====Main Begin=====" << endl; 27 { 28 boost::shared_ptr<Book> myBook(new Book("「1984」")); 29 cout << "[From myBook] The ref count of book is " << myBook.use_count() << ".\n" << endl; 30 31 boost::shared_ptr<Book> myBook1(myBook); 32 cout << "[From myBook] The ref count of book is " << myBook.use_count() << "." << endl; 33 cout << "[From myBook1] The ref count of book is " << myBook1.use_count() << ".\n" << endl; 34 35 cout << "Reset for 1th time. Begin..." << endl; 36 myBook.reset(); 37 cout << "[From myBook] The ref count of book is " << myBook.use_count() << "." << endl; 38 cout << "[From myBook1] The ref count of book is " << myBook1.use_count() << "." << endl; 39 cout << "Reset for 1th time. End ...\n" << endl; 40 41 cout << "Reset for 2th time. Begin ..." << endl; 42 myBook1.reset(); 43 cout << "Reset for 2th time. End ..." << endl; 44 } 45 cout << "===== Main End =====" << endl; 46 47 return 0; 48 }
三、shared_from_this()this
在一个类中须要传递类对象自己shared_ptr的地方使用shared_from_this函数来得到指向自身的shared_ptr,它是enable_shared_from_this的成员函数,返回shared_ptr。spa
这个函数仅在shared_ptr的构造函数被调用以后才能使用。缘由是enable_shared_from_this::weak_ptr并不在enable_shared_from_this构造函数中设置,而是在shared_ptr的构造函数中设置。 指针