boost相关函数

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 }

 

猜你喜欢

转载自www.cnblogs.com/renweihang/p/9915104.html