enable_shared_from_this

enable_shared_from_this是一个模板类,定义于头文件<memory>

share_from_this()是返回指向该对象的share_ptr。

例子

 1 #include <memory>  
 2 #include <iostream>  
 3   
 4 struct Good : std::enable_shared_from_this<Good> // 注意:继承  
 5  6 public 7     std::shared_ptr<Good> getptr() {  
 8         return shared_from_this();  
 9     }  
10     ~Good() { std::cout << "Good::~Good() called" << std::endl; }  
11 };  
12   
13 int main()  
14 15     // 大括号用于限制作用域,这样智能指针就能在system("pause")之前析构  
16     {  
17         std::shared_ptr<Good> gp1(new Good());  
18         std::shared_ptr<Good> gp2 = gp1->getptr();  
19         // 打印gp1和gp2的引用计数  
20         std::cout << "gp1.use_count() = " << gp1.use_count() << std::endl;  
21         std::cout << "gp2.use_count() = " << gp2.use_count() << std::endl;  
22     }  
23     system("pause");  
24 }  
View Code

猜你喜欢

转载自www.cnblogs.com/osbreak/p/9212304.html
今日推荐