1、boost::scoped_ptr是一个比较简单的智能指针,它能保证在离开作用域之后它所管理对象能被自动释放
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 }
2、 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 }
3、shared_from_this()
-
在一个类中需要传递类对象本身shared_ptr的地方使用shared_from_this函数来获得指向自身的shared_ptr,它是enable_shared_from_this的成员函数,返回shared_ptr。
-
这个函数仅在shared_ptr的构造函数被调用之后才能使用。原因是enable_shared_from_this::weak_ptr并不在enable_shared_from_this构造函数中设置,而是在shared_ptr的构造函数中设置。