绑定shared_from_this,内存不会被释放

bind shared_from_this the memory will not be released

本文关键字:内存 释放 shared from this 绑定      更新时间:2023-10-16
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/enable_shared_from_this.hpp>
class A: public boost::enable_shared_from_this<A>
{
    typedef boost::function<int()> GET;
public:
    A()
    {
        std::cout << "A::A() " << this << std::endl;
    }
    ~A()
    {
        std::cout << "A::~A()" << this <<std::endl;
    }
    void set()
    {
        myget=boost::bind(&A::get, shared_from_this()); 
    }

这里有一个问题:当我用shared_from_this()绑定它时,它不会被释放。但是如果我用this (boost::bind(&A::get, this))绑定它,实例将被释放。

    int getI()
    {
        myget();
    }
    inline int get()
    {
        return 1;
    }
private:
    GET myget;
};
void test()
{
    boost::shared_ptr<A> a(new A);
    a->set();
    a->getI();
}
int main()
{
    test();
    return 0;
}

我的问题是:为什么即使程序已经关闭,A的实例也永远不会被释放?

问题是myget变量会阻止析构函数的运行。

所以你甚至不能写

~A() { 
    std::cout << "A::~A()" << this << std::endl; 
    myget = {}; 
}

这就是弱指针被发明的目的。在这种特殊情况下,您可以简单地使用this,因为在A

的生命周期之后无法访问myget