shared_from_this()
   
shared_from_this的使用方法:
#include<iostream>
#include<memory>
class my_practice;
void func1(std::shared_ptr<my_practice> a)
{
    std::cout << a.use_count() << "\n";
}
class my_practice : public std::enable_shared_from_this<my_practice>
{
public:  
    my_practice(int a) : data(a) {}
    void test(int b)
    {
        data = b;
        func1(shared_from_this());        
    }
    std::shared_ptr<my_practice> getShared_ptr()
    {
    	return shared_from_this();
    }
private:  
    int data;    
};
    
    
    哪种情况下我们需要继承std::enable_shared_from_this呢?
   
- 
     使用场合:
 
 当类A被share_ptr管理
 
 ,且在类A的成员函数里需要把当前类对象作为参数传给其他函数时,就需要传递一个指向自身的share_ptr。
 
 在这种情况下类就需要继承enable_shared_from_this,通过shared_from_this来传递类对象。
    
    
    为什么需要用shared_from_this来传递类对象呢?
   
    1.为什么不能直接传递this指针?
    
    因为我们不知道函数是做什么,如果在函数中释放了该指针,那我们的shared_ptr对象还存在,但是在函数中被delete掉的这种情况。
   
    2.可以用shared_ptr<my_class>p(new my_class(*this))吗?
    
    这个相当于创建了一个新的shared_ptr对象,内容和this指针相同,但是是两个不同的智能指针,增加了内存开销,不符合设计逻辑。
   
    
     编译产生 terminate called after throwing an instance of ‘std::bad_weak_ptr’
     
     what(): bad_weak_ptr错误
    
    
    产生上述错误是因为我们创建了一个栈上的对象
   
int main()
{
	my_practice p(1); //这个就是栈上的对象
	p.test(2); 
}
上述代码编译后就会产生上述错误。
    
     正确的我们应该创建一个shared_ptr对象
    
   
int main()
{   
    std::shared_ptr<my_practice> p(new my_practice(1));
    p->test(2);
}
 
版权声明:本文为weixin_42250655原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
