码迷,mamicode.com
首页 > 其他好文 > 详细

enable_shared_from_this

时间:2018-06-22 13:13:48      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:计数   返回   技术   div   hide   sha   none   call   mem   

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

 

enable_shared_from_this

标签:计数   返回   技术   div   hide   sha   none   call   mem   

原文地址:https://www.cnblogs.com/osbreak/p/9212304.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!